C++ STL algorithm, copy() code example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

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++ copy() to assign the values of elements from a source range to a destination range, iterating through the source sequence of elements and assigning them new positions in a forward direction in C++ programming

To show: How to use the C++ algorithm, copy() to assign the values of elements from a source range to a destination range, iterating through the source sequence of elements and assigning them new positions in a forward direction in C++ programming

// C++ STL algorithm, copy()

#include<vector>

#include<algorithm>

#include<iostream>

usingnamespace std;

int main(void)

{

// vector containers

vector <int> vec1, vec2;

// vector iterators

vector <int>::iterator Iter1, Iter2;

int i, j;

// pushing data, constructing vectors

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

vec1.push_back(i);

for(j = 10; j <= 20; j++)

vec2.push_back(j);

// print the data

cout<<"vec1 vector data: ";

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

cout<<*Iter1<<" ";

cout<<endl;

cout<<"vec2 vector data: ";

for(Iter2 = vec2.begin(); Iter2 != vec2.end(); Iter2++)

cout<<*Iter2<<" ";

cout<<endl;

// to copy the first 4 elements of vec1 into the middle of vec2

copy(vec1.begin(), vec1.begin() + 4, vec2.begin() + 5);

// print the result

cout<<"vec2 vector with vec1 vector insert data: ";

for(Iter2 = vec2.begin(); Iter2 != vec2.end(); Iter2++)

cout<<*Iter2<<" ";

cout<<endl;

// to shift the elements inserted into vec2 two positions to the left

copy(vec2.begin()+4, vec2.begin() + 7, vec2.begin() + 2);

// print the result

cout<<"vec2 vector with shifted insert data: ";

for(Iter2 = vec2.begin(); Iter2 != vec2.end(); Iter2++)

cout<<*Iter2<<" ";

cout<<endl;

return 0;

}

Output examples:

vec1 vector data: 0 1 2 3 4 5

vec2 vector data: 10 11 12 13 14 15 16 17 18 19 20

vec2 vector with vec1 vector insert data: 10 11 12 13 14 0 1 2 3 19 20

vec2 vector with shifted insert data: 10 11 14 0 1 0 1 2 3 19 20

Press any key to continue . . .