C++ STL back_insert_iterator::back_insert_iterator 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++ to back_insert_iterator to construct a back_insert_iterator that inserts elements after the last element in a container in C++ programming

To show: How to use the C++ back_insert_iterator to construct a back_insert_iterator that inserts elements after the last element in a container in C++ programming

 

// C++ STL back_insert_iterator, back_insert_iterator

#include <iterator>

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

int i;

// vector container

vector<int> vec;

 

// push/insert data into vector

for (i = 1 ; i < 5 ; ++i)

{

vec.push_back(i);

}

 

// vector iterator

vector <int>::iterator vIter;

 

// print the data

cout<<"The initial vec vector is: ";

for (vIter = vec.begin() ; vIter != vec.end(); vIter++)

cout<<*vIter<<" ";

cout<<endl;

 

// insertions with member function

cout<<endl<<"Insert more data using back_inserter()"<<endl;

back_inserter(vec) = 40;

back_inserter(vec) = 31;

back_inserter(vec) = 21;

back_inserter(vec) = 51;

cout<<"Now, vec vector is: ";

for (vIter = vec.begin() ; vIter != vec.end(); vIter++)

cout<<*vIter<<" ";

cout<<endl;

 

// alternatively, insertions can be done with template function

cout<<endl<<"Insert more data using back_insert_iterator..."<<endl;

back_insert_iterator<vector<int> > backiter(vec);

*backiter = 600;

backiter++;

*backiter = 700;

cout<<"Then, the vec vector is: ";

for (vIter = vec.begin() ; vIter != vec.end(); vIter++)

cout<<*vIter<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The initial vec vector is: 1 2 3 4

Insert more data using back_inserter()

Now, vec vector is: 1 2 3 4 40 31 21 51

Insert more data using back_insert_iterator...

Then, the vec vector is: 1 2 3 4 40 31 21 51 600 700

Press any key to continue . . .

 

 

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