how to check if vector is ordered c++

#include <iostream>
#include <vector>
#include <algorithm>

bool isVectorOrdered(const std::vector<int>& vec) {
    return std::is_sorted(vec.begin(), vec.end());
}

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5};

    if (isVectorOrdered(numbers)) {
        std::cout << "The vector is ordered." << std::endl;
    } else {
        std::cout << "The vector is not ordered." << std::endl;
    }

    return 0;
}

Explanation:

  1. #include <iostream>: Includes the input/output stream library to allow input and output operations.

  2. #include <vector>: Includes the vector library to work with dynamic arrays.

  3. #include <algorithm>: Includes the algorithm library for using algorithms like std::is_sorted.

  4. bool isVectorOrdered(const std::vector<int>& vec): Defines a function isVectorOrdered that takes a constant reference to a vector of integers and returns a boolean value. It uses std::is_sorted from the <algorithm> header to check if the vector is sorted.

  5. std::is_sorted(vec.begin(), vec.end()): Checks whether the elements in the vector, starting from vec.begin() to vec.end(), are sorted in ascending order. It returns true if the vector is sorted; otherwise, it returns false.

  6. int main(): The main function where the program execution starts.

  7. std::vector<int> numbers = {1, 2, 3, 4, 5};: Initializes a vector named numbers with integer values in ascending order.

  8. if (isVectorOrdered(numbers)) { ... } else { ... }: Checks if the numbers vector is ordered by calling the isVectorOrdered function. If the vector is ordered, it prints "The vector is ordered." Otherwise, it prints "The vector is not ordered."

  9. return 0;: Indicates successful program execution by returning 0 to the operating system.