C++ Algorithm 库 - is_sorted() 函数
描述
C++ 函数 std::algorithm::is_sorted() 测试范围是否已排序。 它使用 operator< 进行比较。
声明
以下是 std::algorithm::is_sorted() 函数形式 std::algorithm 头的声明。
C++11
template <class ForwardIterator> bool is_sorted (ForwardIterator first, ForwardIterator last);
参数
first − 将迭代器转发到初始位置。
last − 将迭代器转发到最终位置。
返回值
如果范围已排序,则返回 true,否则返回 false。
异常
如果元素比较或迭代器上的操作引发异常,则引发异常。
请注意,无效参数会导致未定义的行为。
时间复杂度
Linear.
示例
以下示例显示了 std::algorithm::is_sorted() 函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
vector<int> v = {1, 2, 3, 4, 5};
bool result;
result = is_sorted(v.begin(), v.end());
if (result == true)
cout << "Vector elements are sorted in ascending order." << endl;
v[0] = 10;
result = is_sorted(v.begin(), v.end());
if (result == false)
cout << "Vector elements are not sorted in ascending order." << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
Vector elements are sorted in ascending order. Vector elements are not sorted in ascending order.

