c++ check if vector is sorted
To check if a vector is sorted in C++, you can use the std::is_sorted
algorithm from the <algorithm>
library. Here are the steps to check if a vector is sorted:
Include the necessary header files:
cpp #include <vector> #include <algorithm>
This will allow you to use thestd::vector
container and thestd::is_sorted
algorithm.Create a vector:
cpp std::vector<int> numbers = {1, 2, 3, 4, 5};
Replaceint
with the appropriate data type if you're using a different type of vector.Use the
std::is_sorted
algorithm to check if the vector is sorted:cpp bool isSorted = std::is_sorted(numbers.begin(), numbers.end());
This will returntrue
if the vector is sorted in ascending order, andfalse
otherwise.Print the result:
cpp if (isSorted) { std::cout << "The vector is sorted." << std::endl; } else { std::cout << "The vector is not sorted." << std::endl; }
This will output whether the vector is sorted or not.
That's it! You have now checked if a vector is sorted using the std::is_sorted
algorithm in C++.