c++ STL仿函数

仿函数:行为具有函数功能的class的对象就是仿函数。

 仿函数一般有成员函数  ret_type operator()(arguments)const;

 

仿函数的优点:
1.仿函数是对象,可以拥有成员函数和成员变量,即仿函数拥有状态(states)
2.每个仿函数都有自己的类型
3.仿函数通常比一般函数快(很多信息编译期确定)

 

例如:

 

 

[cpp]  view plain copy
  1. class PrintInt {  
  2.   public:  
  3.     void operator() (int elem) const {  
  4.         cout << elem << ' ';  
  5.     }  
  6. };  
  7.   
  8. int main()  
  9. {  
  10.     vector<int> coll;  
  11.   
  12.     // insert elements from 1 to 9  
  13.     for (int i=1; i<=9; ++i) {  
  14.         coll.push_back(i);  
  15.     }  
  16.   
  17.     // print all elements  
  18.     for_each (coll.begin(), coll.end(),    // range  
  19.               PrintInt());                 // operation  
  20.     cout << endl;  
  21. }  


二,预先定义的仿函数

stl中预定义了很多的仿函数。例如:

set<int> coll;

会被扩展成:

set<int, less<int>> coll;

其中less<int>就是一个仿函数(class)。

 

又如

transform(coll.begin(), coll.end(), coll.begin(), negate<int>());

negate<int>()是预定义仿函数。

 

又如

transform(coll.begin(), coll.end(), coll.begin(), coll.begin(), multiplies<int>());

multiplies<int>()是预定义仿函数。

 

 

又如:

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <set>  
  3. #include <deque>  
  4. #include <algorithm>  
  5. #include "print.hpp"  
  6. using namespace std;  
  7.   
  8. int main()  
  9. {  
  10.     set<int,greater<int> > coll1;  
  11.     deque<int> coll2;  
  12.   
  13.     // insert elements from 1 to 9  
  14.     for (int i=1; i<=9; ++i) {  
  15.         coll1.insert(i);  
  16.     }  
  17.   
  18.     PRINT_ELEMENTS(coll1,"initialized: ");  
  19.   
  20.     // transform all elements into coll2 by multiplying 10  
  21.     transform (coll1.begin(),coll1.end(),        // source  
  22.                back_inserter(coll2),             // destination  
  23.                bind2nd(multiplies<int>(),10));   // operation  
  24.   
  25.     PRINT_ELEMENTS(coll2,"transformed: ");  
  26.   
  27.     // replace value equal to 70 with 42  
  28.     replace_if (coll2.begin(),coll2.end(),       // range  
  29.                 bind2nd(equal_to<int>(),70),     // replace criterion  
  30.                 42);                             // new value  
  31.   
  32.     PRINT_ELEMENTS(coll2,"replaced:    ");  
  33.   
  34.     // remove all elements with values less than 50  
  35.     coll2.erase(remove_if(coll2.begin(),coll2.end(), // range  
  36.                           bind2nd(less<int>(),50)),  // remove criterion  
  37.                 coll2.end());  
  38.   
  39.     PRINT_ELEMENTS(coll2,"removed:     ");  
  40. }  


 bind2nd(multiplies<int>()产生一个仿函数。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值