谓词
谓词是一个可调用的表达式,其返回结果是一个能用作条件的值。
标准库算法所用谓词分为两类:
1、一元谓词:意味着只接受单一参数 2、二元谓词:意味着有两个参数
接受谓词的算法对序列的元素调用谓词,因此元素类型必须能转换为谓词的参数类型(并不要求类型一致)
比如下面这个函数就是一个二元谓词,因为有两个参数。
bool isShorter(const string& s1, const string& s2)
{
return s1.size() < s2.size();
}
接受谓词的排序算法可以更多样化,我们可以自定义排序。
以下代码是将重复元素删去,然后将字符串按大小重排,相同长度的字符串按字典序排列。
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
bool isShorter(const string& s1, const string& s2) //按长度排序
{
return s1.size() < s2.size();
}
template<typename T> void print(const T& seq) //模板输出序列中的元素
{
for (auto i : seq)
cout << i << " ";
cout << endl;
}
void elimDups(vecto