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:
#include <iostream>
: Includes the input/output stream library to allow input and output operations.#include <vector>
: Includes the vector library to work with dynamic arrays.#include <algorithm>
: Includes the algorithm library for using algorithms likestd::is_sorted
.bool isVectorOrdered(const std::vector<int>& vec)
: Defines a functionisVectorOrdered
that takes a constant reference to a vector of integers and returns a boolean value. It usesstd::is_sorted
from the<algorithm>
header to check if the vector is sorted.std::is_sorted(vec.begin(), vec.end())
: Checks whether the elements in the vector, starting fromvec.begin()
tovec.end()
, are sorted in ascending order. It returnstrue
if the vector is sorted; otherwise, it returnsfalse
.int main()
: The main function where the program execution starts.std::vector<int> numbers = {1, 2, 3, 4, 5};
: Initializes a vector namednumbers
with integer values in ascending order.if (isVectorOrdered(numbers)) { ... } else { ... }
: Checks if thenumbers
vector is ordered by calling theisVectorOrdered
function. If the vector is ordered, it prints "The vector is ordered." Otherwise, it prints "The vector is not ordered."return 0;
: Indicates successful program execution by returning 0 to the operating system.