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

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

 

// C++ STL iterator, back_inserter()

#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 vecIter;

 

// print the data

cout<<"The vector vec data: ";

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

cout<<*vecIter<<" ";

cout<<endl;

 

// insertions using template function

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

*backiter = 11;

backiter++;

*backiter = 9;

backiter++;

*backiter = 27;

 

cout<<"\nOperation: *backiter = 11 then backiter++..."<<endl;

cout<<"New vector vec data: ";

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

cout<<*vecIter<<" ";

cout<<endl;

 

cout<<"\nOperation: back_inserter(vec) = 21..."<<endl;

// another way, insertions using the back_inserter() member function

back_inserter(vec) = 21;

back_inserter(vec) = 17;

back_inserter(vec) = 33;

cout<<"New vector vec data: ";

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

cout<<*vecIter<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The vector vec data: 1 2 3 4

Operation: *backiter = 11 then backiter++...

New vector vec data: 1 2 3 4 11 9 27

Operation: back_inserter(vec) = 21...

New vector vec data: 1 2 3 4 11 9 27 21 17 33

Press any key to continue . . .

 

 

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