目录
标准库目前提供了约有24个仿函数,分为算数类、逻辑运算类、相对关系类。


| 操作 | 仿函数 |
|---|---|
| 加 | plus |
| 减 | minus |
| 乘 | multiplies |
| 除 | divides |
| 取模 | modulus |
| 取反 | negate |
使用 multiplies 乘 仿函数:
- #include
- #include
- #include
- #include
- using namespace std;
-
- int func(){
- static int i=1;
- return i++;
- }
- /*
- int mulitply(int res,int n){
- return res*n;
- }
- */
- int main(){
- vector<int> vec(10);
- generate(vec.begin(),vec.end(),func);
- for(auto n:vec){
- cout << n << " ";
- }
- cout << endl;
-
- // int res = accumulate(vec.begin(),vec.end(),1,mulitply);
- int res = accumulate(vec.begin(),vec.end(),1,multiplies<int>()); // 使用STL中的仿函数
- cout << res << endl;
- }
运行结果:
- 1 2 3 4 5 6 7 8 9 10
- 3628800
| 操作 | 仿函数 |
|---|---|
| 等于 | equal_to |
| 不等于 | not_equal_to |
| 大于 | greater |
| 大于等于 | greater_equal |
| 小于 | less |
| 小于等于 | less_equal |
| 操作 | 仿函数 |
|---|---|
| 逻辑与 | logical_and |
| 逻辑或 | logical_or |
| 逻辑否 | logical_not |
下图中myclass是我们自己写的仿函数,但是由于没有继承仿函数的公共父类,所以就不能融入到STL中。

如果我们要自己写仿函数,并且融入到STL中, 就必须继承两个中的一个父类(两个操作符的父类或者一个操作符的父类),只有继承了才能被适配器去修饰和改造。
