C++ STL deque, insert() program 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 the deque at a specified position in C++ programming

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

 

// C++ STL deque, insert()

#include <deque>

#include <iostream>

using namespace std;

 

int main(void)

{

// deque container

deque <int> con1, con2;

// deque iterator

deque <int>::iterator Iter;

 

// push/insert data into deque

con1.push_back(10);

con1.push_back(20);

con1.push_back(30);

con2.push_back(40);

con2.push_back(50);

con2.push_back(60);

 

// print the data and do some operations

cout<<"con1 deque: ";

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

cout<<*Iter<<" ";

cout<<endl;

Iter = con1.begin();

Iter++;

con1.insert(Iter, 100);

cout<<"\nOperation: con1.insert(Iter, 100);"<<endl;

cout<<"con1 deque: ";

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

cout<<*Iter<<" ";

cout<<endl;

Iter = con1.begin();

Iter++;

Iter++;

con1.insert(Iter, 2, 200);

cout<<"\nOperation: con1.insert(Iter, 2, 200);"<<endl;

cout<<"con1 deque: ";

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

cout<<*Iter<<" ";

cout<<endl;

con1.insert(++con1.begin(), con2.begin(),--con2.end());

cout<<"\nOperation: con1.insert(++con1.begin(), con2.begin(),--con2.end());"<<endl;

cout<<"con1 deque: ";

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

cout<<*Iter<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

con1 deque: 10 20 30

Operation: con1.insert(Iter, 100);

con1 deque: 10 100 20 30

Operation: con1.insert(Iter, 2, 200);

con1 deque: 10 100 200 200 20 30

Operation: con1.insert(++con1.begin(), con2.begin(),--con2.end());

con1 deque: 10 40 50 100 200 200 20 30

Press any key to continue . . .

 

 

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