C++ STL  iterator, front_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 the C++ iterator, front_inserter() to create an iterator that can insert elements at the front of a specified container in C++ programming

To show: How to use the C++ iterator, front_inserter() to create an iterator that can insert elements at the front of a specified container in C++ programming

 

// C++ STL iterator, front_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;

 

// push/insert data

for(i = -2; i<=5; ++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;

 

// using the template function to insert an element

cout<<"\nOperation: ++Iter then *Iter = 12..."<<endl;

front_insert_iterator< list <int> > Iter(lst);

*Iter = 21;

++Iter;

*Iter = 12;

 

// print the data

cout<<"New list lst data: ";

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

cout<<*lstiter<<" ";

cout<<endl;

 

cout<<"\nOperation: front_inserter(lst) = 23..."<<endl;

// another way, using the front_insert() member function

front_inserter(lst) = 23;

front_inserter(lst) = 9;

 

// print the data

cout<<"New list lst data: ";

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

cout<<*lstiter<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The list lst data: -2 -1 0 1 2 3 4 5

Operation: ++Iter then *Iter = 12...

New list lst data: 12 21 -2 -1 0 1 2 3 4 5

Operation: front_inserter(lst) = 23...

New list lst data: 9 23 12 21 -2 -1 0 1 2 3 4 5

Press any key to continue . . .

 

 

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