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:

  1. Include the necessary header files: cpp #include <vector> #include <algorithm> This will allow you to use the std::vector container and the std::is_sorted algorithm.

  2. Create a vector: cpp std::vector<int> numbers = {1, 2, 3, 4, 5}; Replace int with the appropriate data type if you're using a different type of vector.

  3. 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 return true if the vector is sorted in ascending order, and false otherwise.

  4. 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++.