ccplusplus.com
Learn C, C++ Concepts
Saturday, January 14, 2012
stl function adaptors
/*********************************************************************** * File : function-adapters.cpp * Author : Saurabh Gupta * Desc : stl function adaptors * Source : http://ccplusplus/2011/10/standard-template-library.html * Created : PM 11:57 13 January 2012 * Note : ************************************************************************/ #include
#include
#include
#include
using namespace std; /* printElements() * - prints optional C-string optcstr followed by * - all elements of the collection coll * - separated by spaces */ template
inline void printElements (const T& coll, const char* optcstr="") { typename T::const_iterator pos; cout << optcstr; for (pos=coll.begin(); pos!=coll.end(); ++pos) { cout << *pos << ' '; } cout << endl; } int main() { set
> coll1; deque
coll2; /* * insert elements from 1 to 9 */ for (int i=1; i<=9; ++i) { coll1.insert(i); } printElements(coll1,"initialized: "); /* * transform all elements into coll2 by multiplying 10 */ transform (coll1 .begin(), coll1 .end(), //source back_inserter(coll2), //destination bind2nd(multiplies
() ,10)); //operation printElements(coll2,"transformed: "); /* * replace value equal to 70 with 42 */ replace_if (coll2.begin(),coll2.end(), //range bind2nd(equal_to
() ,70) , //replace criterion 42) ; //new value printElements(coll2,"replaced: "); /* * remove all elements with values less than 50 */ coll2.erase(remove_if(coll2.begin(),coll2.end(), //range bind2nd(less
() ,50)), //remove criterion coll2.end()); printElements(coll2,"removed: "); } /* * OUTPUT * [sgupta@rhel6x64 predefined-function-object]$ c++ function-adapters.cpp -o function-adapters [sgupta@rhel6x64 predefined-function-object]$ ./function-adapters initialized: 9 8 7 6 5 4 3 2 1 transformed: 90 80 70 60 50 40 30 20 10 replaced: 90 80 42 60 50 40 30 20 10 removed: 90 80 60 50 [sgupta@rhel6x64 predefined-function-object]$ */
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment