class Add {
public:
int operator()(int a,int b) {
return a + b;
}
};
class Print {
public:
Print() {
this->count = 0;
}
void operator()(string avg) {
cout << avg;
this->count++;
}
int count;
};
void doPrint(Print &p,string r) {
p(r);
}
void test() {
Add add;
cout<<add(1,10); // 作为函数调用
Print p;
p("hello");
p("hello");
p("hello");
p("hello");
cout << p.count << endl; //统计调用次数
doPrint(p,"nihao"); //作为参数
}
一元谓词
class CompareThree {
public:
bool operator()(int val) {
return val > 5;
}
};
void test() {
vector<int>v;
for (int i = 5; i < 9; i++) {
v.push_back(i);
}
vector<int>::iterator it = find_if(v.begin(),v.end(),CompareThree());
if (it == v.end()) {
cout << "没找到" << endl;
}
else {
cout << *it << endl;
}
}
二元谓词
class Compare {
public:
bool operator()(int a,int b) {
return a > b;
}
};
void test() {
vector<int>v;
for (int i = 1; i < 9; i++) {
v.push_back(rand()%i);
}
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
cout << "\n";
sort(v.begin(), v.end(),Compare());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
}
STL内建了一些函数对象,需要引入头文件 #include
1、算术仿函数
函数类型如下
negate<int>n;
cout<<n(5);
plus<int>p;
cout<<p(1, 3);
2、关系仿函数
实现关系对比
void test() {
greater<int>g;
vector<int>v;
v.push_back(14);
v.push_back(4);
v.push_back(1);
v.push_back(15);
sort(v.begin(), v.end(),greater<int>()); //使用内置仿函数
sort(v.begin(), v.end(),Compare()); // 自定义仿函数
for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
cout << *it << " ";
}
}
3、逻辑仿函数
逻辑运算通常包括与、或、非。与同时取真为真;或取任一为真即为真;非取相反状态。
logical_not<bool>l;
cout << l(12);
vector<int>v;
v.push_back(14);
v.push_back(4);
v.push_back(0);
v.push_back(15);
vector<int>v1;
v1.resize(4);
transform(v.begin(),v.end(),v1.begin(), logical_not<int>()); //逻辑仿函数
for (vector<int>::iterator it = v1.begin(); it != v1.end(); it++) {
cout << *it << " ";
}