C++ STL iterator, inserter() program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using th C++ as a helper template function that lets you use inserter(_Cont,_Where) instead of insert_iterator<Container>(_Cont,_Where) in C++ programming
To show: How to use the C++ iterator, inserter() as a helper template function that lets you use inserter(_Cont,_Where) instead of insert_iterator<Container>(_Cont,_Where) in C++ programming
// C++ STL iterator, inserter()
#include <iterator>
#include <list>
#include <iostream>
using namespace std;
int main(void)
{
int i;
// list iterator
list <int>::iterator lstiter;
// list container
list<int> lst;
// insert/push data into the list
for(i = -3; i<=2; ++i)
lst.push_back(i);
// print the data
cout<<"The list lst data: ";
for(lstiter = lst.begin(); lstiter != lst.end(); lstiter++)
cout<<*lstiter<<" ";
cout<<endl;
// insert more data
// using the template version to insert elements
insert_iterator<list <int> > Iter(lst, lst.begin());
*Iter = 7;
++Iter;
*Iter = 12;
cout<<"\nOperation: *Iter = 7 then ++Iter..."<<endl;
cout<<"After the insertions, the list lst data: ";
for(lstiter = lst.begin(); lstiter != lst.end(); lstiter++)
cout<<*lstiter<<" ";
cout<<endl;
// another way, using the member function inserter() to insert an element
inserter(lst, lst.end()) = 31;
inserter(lst, lst.end()) = 42;
cout<<"\nOperation: inserter(lst, lst.end()) = 42..."<<endl;
cout<<"After the insertions, the list lst data: ";
for(lstiter = lst.begin(); lstiter != lst.end(); lstiter++)
cout<<*lstiter<<" ";
cout<<endl;
return 0;
}
Output examples:
The list lst data: -3 -2 -1 0 1 2
Operation: *Iter = 7 then ++Iter...
After the insertions, the list lst data: 7 12 -3 -2 -1 0 1 2
Operation: inserter(lst, lst.end()) = 42...
After the insertions, the list lst data: 7 12 -3 -2 -1 0 1 2 31 42
Press any key to continue . . .