ccplusplus.com
Learn C, C++ Concepts
Saturday, January 7, 2012
inserters c++
/*********************************************************************** * File : insert-iterator.cpp * Author : Saurabh Gupta * Desc : inserters c++ * Source : http://ccplusplus/2011/10/standard-template-library.html * Created : PM 11:30 07 January 2012 * Note : ************************************************************************/ #include <vector> #include <list> #include <deque> #include <set> #include <algorithm> #include <iostream> using namespace std; int main() { list<int> coll1; /* * insert elements from 1 to 9 into the first collection */ for (int i=1; i<=9; ++i) { coll1.push_back(i); } list<int>::iterator it1; cout << "coll1 contains:"; for ( it1=coll1.begin() ; it1 != coll1.end(); it1++ ) { cout << " " << *it1; } cout << "" << endl; /* * copy the elements of coll1 into coll2 by appending them */ vector<int> coll2; copy (coll1.begin(), coll1.end(), //source back_inserter(coll2)); //destination vector<int>::iterator it2; cout << "coll2 contains:"; for ( it2=coll2.begin() ; it2 != coll2.end(); it2++ ) { cout << " " << *it2; } cout << "" << endl; /* * copy the elements of coll1 into coll3 by inserting them at the front * reverses the order of the elements */ deque<int> coll3; copy (coll1.begin(), coll1.end(), //source front_inserter(coll3)); //destination deque<int>::iterator it3; cout << "coll3 contains:"; for ( it3=coll3.begin() ; it3 != coll3.end(); it3++ ) { cout << " " << *it3; } cout << "" << endl; /* * copy elements of coll1 into coll4 * only inserter that works for associative collections */ set<int> coll4; copy (coll1.begin(), coll1.end(), //source inserter(coll4,coll4.begin())); //destination set<int>::iterator it4; cout << "coll4 contains:"; for ( it4=coll4.begin() ; it4 != coll4.end(); it4++ ) { cout << " " << *it4; } cout << "" << endl; return 0; } /* * OUTPUT * [sgupta@rhel6x64 stl]$ c++ insert-iterator.cpp -o insert-iterator [sgupta@rhel6x64 stl]$ ./insert-iterator coll1 contains: 1 2 3 4 5 6 7 8 9 coll2 contains: 1 2 3 4 5 6 7 8 9 coll3 contains: 9 8 7 6 5 4 3 2 1 coll4 contains: 1 2 3 4 5 6 7 8 9 [sgupta@rhel6x64 stl]$ */
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