C++ conut_if和谓词使用

来源:百度知道 编辑:UC知道 时间:2024/06/08 17:25:24
#include <iostream>
#include <vector>
#include <algorithm>
#include <cctype>
using namespace std;

class Pred
{
private:
int _val;
public:
Pred(int val):_val(val) {}
bool operator()(int val) { return val>_val; }
};

int main()
{
int n, array_size, num[] = { 6, 139, 8, 4, 122, 56, 985,44};
vector<int> vec_i;
Pred w(100);
//Pred(100) ww;

array_size = sizeof(num)/sizeof(num[0]);

for (int i=0; i < array_size; i++) vec_i.push_back(num[i]);

n = count_if(vec_i.begin(),vec_i.end(),Pred(44));//Pred(44) ,请问高手这个是什么用法,我不明白,为什么可以这样调用一个类??
cout << n;

system("pause");
return 0;
}

n = count_if(vec_i.begin(),vec_i.end(),Pred(44));//Pred(44) ,请问高手这个是什么用法,我不明白,为什么可以这样调用一个类??
我明白这个含义

STL中,这都叫做可被调用(callable)的东西。
可以是函数,也可以是一个仿函数(functor),就是一个重载了operator()的函数。

看到struct后面跟了()就表示有一个临时对象给产生了。然后count_if里面会调用operator()

bool operator()(int val) { return val>_val; }
这个地方重载操作符了
Pred(44)相当于(44>_val)表达式

Pred(44) 是对函数的委托。可以通过delegate关键字来定义一种函数的委托。

这个叫仿函数,STL里大量使用。