C++ STL algorithm, insert(), copy(), display() and resize() 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++ insert(), copy(), display() and resize() in C++ programming for vector, list and deque containers

To show: How to use the C++ algorithm, insert(), copy(), display() and resize() for vector, list and deque containers in C++ programming

 

// C++ STL algorithm, insert(), copy(), display() and resize()

#include <iostream>

#include <vector>

#include <list>

#include <deque>

#include <algorithm>

using namespace std;

 

int main(void)

{

// list container

list<int> lst1;

// list iterator

list<int>::iterator pos;

// vector container

vector<int> vec1;

// vector iterator

vector<int>::iterator pos1;

 

// push/insert elements from 1 to 10, constructing a list

for(int i=1; i<=10; ++i)

lst1.push_back(i);

 

// display data

cout<<"The lst1 list data: ";

for(pos=lst1.begin(); pos!=lst1.end(); pos++)

cout<<*pos<<" ";

cout<<endl;

 

// resize destination to have enough room for the overwriting algorithm

vec1.resize(lst1.size());

// copy elements from first into second collection overwrites existing elements in destination

copy(lst1.begin(), lst1.end(), // source

vec1.begin()); // destination

// printing the result

cout<<"\nThe vec1 vector data: ";

for(pos1=vec1.begin(); pos1!=vec1.end(); pos1++)

cout<<*pos1<<" ";

cout<<endl;

// create third collection with enough allocation, initial size is passed as parameter

//

// deque container

deque<int> deq1(lst1.size());

// deque iterator

deque<int>::iterator pos2;

// some operations, copy elements from first into third collection

copy(lst1.begin(), lst1.end(), //source

deq1.begin()); // destination

// print the result

cout<<"\nThe deq1 deque data: ";

for(pos2=deq1.begin(); pos2!=deq1.end(); pos2++)

cout<<*pos2<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The lst1 list data: 1 2 3 4 5 6 7 8 9 10

The vec1 vector data: 1 2 3 4 5 6 7 8 9 10

The deq1 deque data: 1 2 3 4 5 6 7 8 9 10

Press any key to continue . . .

 

 

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