ccplusplus.com
Learn C, C++ Concepts
Wednesday, January 11, 2012
stl transform algorithm c++
/*********************************************************************** * File : transform.cpp * Author : Saurabh Gupta * Desc : stl transform algorithm c++ * Source : http://ccplusplus/2011/10/standard-template-library.html * Created : PM 07:33 11 January 2012 * Note : ************************************************************************/ #include <iostream> #include <vector> #include <set> #include <algorithm> /* printElements() * - prints optional C-string optcstr followed by * - all elements of the collection coll * - separated by spaces */ template <class T> inline void printElements (const T& coll, const char* optcstr="") { typename T::const_iterator pos; std::cout << optcstr; for (pos=coll.begin(); pos!=coll.end(); ++pos) { std::cout << *pos << ' '; } std::cout << std::endl; } int square (int value) { return value*value; } int main() { std::set<int> coll1; std::vector<int> coll2; //insert elements from 1 to 9 into coll1 for (int i=1; i<=9; ++i) { coll1.insert(i); } printElements(coll1,"initialized: "); //transform each element from coll1 to coll2 // - square transformed values std::transform (coll1.begin(),coll1.end(), //source std::back_inserter(coll2), //destination square); //operation printElements(coll2,"squared: "); } /* * OUTPUT * [sgupta@rhel6x64 algorithm]$ c++ transform.cpp -o transform [sgupta@rhel6x64 algorithm]$ ./transform initialized: 1 2 3 4 5 6 7 8 9 squared: 1 4 9 16 25 36 49 64 81 [sgupta@rhel6x64 algorithm]$ */
See Also:
Standard Template Library Concepts and sample codes in C++
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment