【STL】函数对象
1、函数对象
- 重载函数调用操作符的类,其对象称为函数对象。
- 函数对象使用重载的 () 时,行为类似函数调用,也叫仿函数。
- 函数对象是一个类,不是一个函数。
使用 - 函数对象在使用时,可以像普通函数那样调用,可以有参数,也可以有返回值
- 函数对象超出普通函数的概念,可以有自己的成员
- 函数对象可以作为参数。
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"); //作为参数
}
2、谓词
- 返回bool类型的仿函数称为谓词
- 如果operator()接受一个参数,那么叫做一元谓词
- 如果operator()接收两个参数,则叫做二元谓词
一元谓词
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 << " ";}
}
3、内建函数对象
STL内建了一些函数对象,需要引入头文件 #include
- 算数仿函数
- 关系仿函数
- 逻辑仿函数
1、算术仿函数
- 实现四则运算
- 其中negate是一元运算,其余为二元
函数类型如下
- template T Plus; 加
- template T negate; 取反
negate<int>n;cout<<n(5);plus<int>p;cout<<p(1, 3);
2、关系仿函数
实现关系对比
- template bool greater; 大于
- template bool less; 小于
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、逻辑仿函数
逻辑运算通常包括与、或、非。与同时取真为真;或取任一为真即为真;非取相反状态。
- templatebool logical_and; 逻辑与
- templatebool logical_or; 逻辑或
- templatebool logical_not; 逻辑非
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 << " ";}