C++ STL algorithm, swap() code 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 swap() to exchange the values of the elements between two types of objects, assigning the contents of the first object to the second object and the contents of the second to the first in C++ programming

To show: How to use the C++ algorithm, swap() to exchange the values of the elements between two types of objects, assigning the contents of the first object to the second object and the contents of the second to the first in C++ programming

 

// C++ STL algorithm, swap()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

bool greaterthan(int value)

{return value > 5;}

 

int main(void)

{

// vector containers

vector <int> vec1, vec2;

// vector iterators

vector <int>::iterator Iter1, Iter2, result;

int i, j;

 

// push data into the vectors

for(i = 20; i<= 30; i++)

vec1.push_back(i);

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

vec2.push_back(j);

 

// print the data

cout<<"vec1 vector data is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

cout<<"\nvec2 vector data is: ";

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

cout<<*Iter2<<" ";

cout<<endl;

swap(vec1, vec2);

cout<<"\nNow after swapping elements, vec1 vector data is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

cout<<"\nThen, vec2 vector data is: ";

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

cout<<*Iter2<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

vec1 vector data is: 20 21 22 23 24 25 26 27 28 29 30

vec2 vector data is: 10 11 12 13 14 15

Now after swapping elements, vec1 vector data is: 10 11 12 13 14 15

Then, vec2 vector data is: 20 21 22 23 24 25 26 27 28 29 30

Press any key to continue . . .

 

 

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