algorithm::is_sorted()
描述 (Description)
C ++函数std::algorithm::is_sorted()测试范围是否排序。 它使用二进制函数进行比较。
声明 (Declaration)
以下是std :: algorithm :: is_sorted()函数形式std :: algorithm头的声明。
C++11
template <class ForwardIterator, class Compare>
bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);
参数 (Parameters)
first - 将迭代器转发到初始位置。
last - 将迭代器转发到最终位置。
comp - 一个二进制函数,它接受两个参数并返回bool。
返回值
如果范围已排序,则返回true,否则返回false。
异常 (Exceptions)
如果二元函数或迭代器上的操作抛出异常,则抛出异常。
请注意,无效参数会导致未定义的行为。
时间复杂
线性。
例子 (Example)
以下示例显示了std :: algorithm :: is_sorted()函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool ignore_case(char a, char b) {
return (tolower(a) == tolower(b));
}
int main(void) {
vector<char> v = {'A', 'b', 'C', 'd', 'E'};
bool result;
result = is_sorted(v.begin(), v.end());
if (result == false)
cout << "Vector elements are not sorted in ascending order." << endl;
result = is_sorted(v.begin(), v.end(), ignore_case);
if (result == true)
cout << "Vector elements are sorted in ascending order." << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 -
Vector elements are not sorted in ascending order.
Vector elements are sorted in ascending order.