谓词
定义
谓词是指普通函数或重载的operator()的仿函数 返回值是bool类型。
使用方式
class GreaterThan20
{
public:
bool operator()(int val)
{
return val> 20;
}
};
int main()
{
vector<int> v;
v.push_back(10);
v.push_back(20);
v.push_back(30);
v.push_back(40);
vector<int>::iterator ret = find_if(v.begin(), v.end(), GreaterThan20());
if (ret != v.end())
{
cout << "找到了大于20的数字" << *ret << endl;
}
else
{
cout << "未找到" << endl;
}
return 0;
}
void myPrintInt(int val)
{
cout << val << " ";
}
class myCompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
int main()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(20);
v.push_back(40);
sort(v.begin(), v.end());
sort(v.begin(), v.end(), myCompare());
for_each(v.begin(), v.end(), myPrintInt);
return 0;
}
拓展:介绍一下lambda表达式
void myPrintInt(int val)
{
cout << val << " ";
}
class myCompare
{
public:
bool operator()(int v1, int v2)
{
return v1 > v2;
}
};
int main()
{
vector<int> v;
v.push_back(10);
v.push_back(30);
v.push_back(20);
v.push_back(40);
sort(v.begin(), v.end(), myCompare());
for_each(v.begin(), v.end(), [](int val) {cout << val << " "; });
return 0;
}
|