在 STL 中,我们需要对一组数据进行排序之前,可以首先使用 is_sorted 函数对数据进行判断,判断其是否已经排序好了,如果没有排序好,再次进行排序。
#include <algorithm>
//判断 [first, last) 区域内的数据是否符合 std::less<T> 排序规则,即是否为升序序列
bool is_sorted (ForwardIterator first, ForwardIterator last);
判断 [first, last) 区域内的数据是否符合 comp 排序规则
bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);
参数 | 描述 |
---|---|
first | 正向迭代器 |
last | 正向迭代器 |
comp | 自定义排序规则 |
其中,first 和 last 都为正向迭代器(这意味着该函数适用于大部分容器),[first, last) 用于指定要检测的序列;comp 用于指定自定义的排序规则。
如果使用默认的升序排序规则,则 [first, last) 指定区域内的元素必须支持使用 < 小于运算符做比较;同样,如果指定排序规则为 comp,也要保证 [first, last) 区域内的元素支持该规则内部使用的比较运算符。
另外,该函数会返回一个 bool 类型值,即如果 [first, last) 范围内的序列符合我们指定的排序规则,则返回 true;反之,函数返回 false。值得一提得是,如果 [first, last) 指定范围内只有 1 个元素,则该函数始终返回 true。
使用 STL is_sorted 函数判断是否已经排序
#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(myvector.begin(), myvector.end(), mycomp1()))
{
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(mylist.begin(), mylist.end()))
{
cout << "开始对 mylist 排序" << endl;
}
else
{
cout << "mylist不需要排序" << endl;
}
return 0;
}
我们在 Linux 下使用 g++ 进行编译,具体命令如下:
g++ is_sorted.cpp -std=c++11
编译后,我们直接运行生成的二进制文件 a.out
,如下图所示:
我们首先,使用了 is_sorted 函数,判断未排序的 vector,结果输出了 false,接着,我们使用了 is_sorted 函数,判断已经排序好的 list,结果返回了 true。
在 STL 中,我们需要对一组数据进行排序之前,可以首先使用 is_sorted 函数对数据进行判断,判断其是否已经排序好了,如果没有排序好,再次进行排序。