C++ STL list, insert() code example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

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() to insert an element or a number of elements or a range of elements into a list at a specified position in C++ programming

To show: How to use the C++ list, insert() to insert an element or a number of elements or a range of elements into a list at a specified position in C++ programming

 

// C++ STL list, insert()

#include <list>

#include <iostream>

using namespace std;

 

int main(void)

{

// list containers

list <int> lis1, lis2;

// list iterator

list <int>::iterator Iter;

 

// insert/push data into the list

lis1.push_back(13);

lis1.push_back(22);

lis1.push_back(15);

lis2.push_back(9);

lis2.push_back(5);

lis2.push_back(45);

 

// do some operations and print the data

cout<<"lis1 list data: ";

for(Iter = lis1.begin(); Iter != lis1.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

cout<<"lis2 list data: ";

for(Iter = lis2.begin(); Iter != lis2.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

cout<<"\nOperation1: lis1.begin() then Iter++..."<<endl;

cout<<"Operation2: lis1.insert(Iter, 55);"<<endl;

Iter = lis1.begin();

Iter++;

lis1.insert(Iter, 55);

cout<<"lis1 list data: ";

for(Iter = lis1.begin(); Iter != lis1.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

cout<<"\nOperation1: lis1.begin() then Iter++..."<<endl;

cout<<"Operation2: lis1.insert(Iter, 3, 30);"<<endl;

Iter = lis1.begin();

Iter++;

Iter++;

lis1.insert(Iter, 3, 30);

cout<<"lis1 list data: ";

for(Iter = lis1.begin(); Iter != lis1.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

cout<<"\nOperation2: lis1.insert(++lis1.begin(), lis2.begin(),--lis2.end());"<<endl;

lis1.insert(++lis1.begin(), lis2.begin(),--lis2.end());

cout<<"lis1 list data: ";

for(Iter = lis1.begin(); Iter != lis1.end(); Iter++)

cout<<" "<<*Iter;

cout<<endl;

return 0;

}

 

Output examples:

 

lis1 list data: 13 22 15

lis2 list data: 9 5 45

Operation1: lis1.begin() then Iter++...

Operation2: lis1.insert(Iter, 55);

lis1 list data: 13 55 22 15

Operation1: lis1.begin() then Iter++...

Operation2: lis1.insert(Iter, 3, 30);

lis1 list data: 13 55 30 30 30 22 15

Operation2: lis1.insert(++lis1.begin(), lis2.begin(),--lis2.end());

lis1 list data: 13 9 5 55 30 30 30 22 15

Press any key to continue . . .

 

 

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