C++ STL  insert_iterator::insert_iterator program sample

 

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 the C++ insert_iterator to construct an insert_iterator that inserts an element into a specified position in a container in C++ programming

To show: How to use the C++ insert_iterator to construct an insert_iterator that inserts an element into a specified position in a container in C++ programming

 

 

 

// C++ STL insert_iterator

#include <iterator>

#include <list>

#include <iostream>

using namespace std;

 

int main()

{

int i;

// list iterator

list <int>::iterator lstiter;

// list container

list<int> lst;

 

// insert/push data

for(i = 10; i<15; ++i)

lst.push_back(i);

 

// print the data

cout<<"The lst list data: ";

for(lstiter = lst.begin(); lstiter != lst.end(); lstiter++)

cout<<*lstiter<<" ";

cout<<endl;

 

// using the member function to insert an element

cout<<"\nOperation: inserter(lst, lst.begin()) = 21...";

inserter(lst, lst.begin()) = 21;

inserter(lst, lst.begin()) = 27;

cout<<"\nAfter the insertions, the lst list data: ";

for(lstiter = lst.begin(); lstiter != lst.end(); lstiter++)

cout<<*lstiter<<" ";

cout<<endl;

 

// another way, using the template version

cout<<"\nOperation: Iter(lst, lst.end()) and *Iter = 9...";

insert_iterator< list <int> > Iter(lst, lst.end());

*Iter = 9;

*Iter = 33;

cout<<"\nAfter the insertions, the lst list data: ";

for(lstiter = lst.begin(); lstiter != lst.end(); lstiter++)

cout<<*lstiter<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The lst list data: 10 11 12 13 14

Operation: inserter(lst, lst.begin()) = 21...

After the insertions, the lst list data: 27 21 10 11 12 13 14

Operation: Iter(lst, lst.end()) and *Iter = 9...

After the insertions, the lst list data: 27 21 10 11 12 13 14 9 33

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index