您的位置:首页 > 其它

stl 学习笔记 8

2007-11-28 00:23 323 查看
function object 仿函数


//stl/ foreach2.cpp






/**//*


using function object


*/


#include <iostream>


#include <vector>


#include <algorithm>


using namespace std;






/**//*


function object(仿函数,函数对象)


*/




class PrintInt...{


public:




void operator() (int elem) const...{


cout << elem<<' ';


}


};






int main()




...{


vector<int> coll;


for(int i =1; i<= 9; ++i)


coll.push_back(i);




for_each(coll.begin(),coll.end(),PrintInt());


cout<<endl;


}




// result




/**//*


1 2 3 4 5 6 7 8 9


*/


//stl/add1.cpp




/**//*


using function object


*/


#include <iostream>


#include <list>


#include <algorithm>


#include "print.h"


using namespace std;






/**//*


function object AddValue


*/




class AddValue...{




public:


AddValue(int v): theValue(v)




...{}




void operator() (int & elem) const




...{


elem += theValue;


}


private:


int theValue;


};




int main()




...{


list<int> coll;




for(int i = 1; i<=9; ++i)




...{


coll.push_back(i);


}




PRINT_ELEMENTS(coll,"initialized: ");




for_each(coll.begin(),coll.end(),AddValue(10));




PRINT_ELEMENTS(coll,"after adding 10:");




for_each(coll.begin(),coll.end(),AddValue(*coll.begin()));




PRINT_ELEMENTS(coll,"after adding first element:");




return 1;


}




// result




/**//*


initialized: 1 2 3 4 5 6 7 8 9


after adding 10:11 12 13 14 15 16 17 18 19


after adding first element:22 23 24 25 26 27 28 29 30


*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: