STL is_sorted_until函数

STL is_sorted_until函数算法

STL 中,is_sorted_until 函数和 is_sorted() 函数相比,不仅能检测出某个序列是否有序,还会返回一个正向迭代器,该迭代器指向的是当前序列中第一个破坏有序状态的元素。

STL is_sorted_until函数详解

头文件

#include <algorithm>

语法

//排序规则为默认的升序排序 ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last); //排序规则是自定义的 comp 规则 ForwardIterator is_sorted_until (ForwardIterator first, ForwardIterator last, Compare comp);

参数

参数 描述
first 正向迭代器
last 正向迭代器
comp 自定义排序规则

说明

其中,first 和 last 都为正向迭代器(这意味着该函数适用于大部分容器),[first, last) 用于指定要检测的序列;comp 用于指定自定义的排序规则。

技术细节

注意,如果使用默认的升序排序规则,则 [first, last) 指定区域内的元素必须支持使用 < 小于运算符做比较;同样,如果指定排序规则为 comp,也要保证 [first, last) 区域内的元素支持该规则内部使用的比较运算符。

可以看到,该函数会返回一个正向迭代器。对于第一种语法格式来说,该函数返回的是指向序列中第一个破坏升序规则的元素;对于第二种语法格式来说,该函数返回的是指向序列中第一个破坏 comp 排序规则的元素。

注意,如果 [first, last) 指定的序列完全满足默认排序规则或者 comp 排序规则的要求,则该函数将返回一个和 last 迭代器指向相同的正向迭代器。

案例

STL is_sorted_until函数

使用 STL is_sorted_until 函数判断是否已经排序

#include <iostream> #include <algorithm> #include <vector> #include <list> using namespace std; class mycomp1 { public: bool operator() (int i, int j) { return (i > j); } }; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; vector<int> myvector{1024, 99, 109, 100}; list<int> mylist{99, 100, 109, 1024}; if ( is_sorted_until(myvector.begin(), myvector.end(), mycomp1()) != myvector.end() ) { cout << "开始对 myvector 容器排序" << endl; sort(myvector.begin(), myvector.end(), mycomp1()); for (auto it = myvector.begin(); it != myvector.end(); ++it) { cout << *it << " "; } } cout << endl; if (is_sorted_until(mylist.begin(), mylist.end()) != mylist.end()) { cout << "开始对 mylist 排序" << endl; } else { cout << "mylist不需要排序" << endl; } return 0; }

我们在 Linux 下使用 g++ 进行编译,具体命令如下:

g++ is_sorted_until.cpp -std=c++11

编译后,我们直接运行生成的二进制文件 a.out,如下图所示:

07_STL is_sorted_until函数.png

我们首先,使用了 is_sorted_until 函数,判断未排序的 vector,接着,我们使用了 is_sorted_until 函数,判断已经排序好的 list,并将结果与 end 迭代器进行比较。

STL is_sorted_until函数总结

在 STL 中,is_sorted_until 函数和 is_sorted() 函数相比,不仅能检测出某个序列是否有序,还会返回一个正向迭代器,该迭代器指向的是当前序列中第一个破坏有序状态的元素。