C++ STL algorithm, swap_ranges() 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_ranges() to exchange the elements of one range with the elements of another, equal sized range in C++ programming

To show: How to use the C++ algorithm, swap_ranges() member to exchange the elements of one range with the elements of another, equal sized range in C++ programming

 

// C++ STL algorithm, swap_ranges()

#include <vector>

#include <deque>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector and deque containers

vector <int> vec1;

deque <int> deq1;

// vector and  deque iterators

vector <int>::iterator vec1Iter1;

deque<int>::iterator deq1Iter;

int i, j;

 

// push data in ranges into the vector and deque

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

vec1.push_back(i);

for(j =24; j <= 29; j++)

deq1.push_back(j);

 

// print the data

cout<<"vec1 vector data: ";

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

cout<<*vec1Iter1<<" ";

cout<<endl;

cout<<"\ndeq1 deque data: ";

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

cout<<*deq1Iter<<" ";

cout<<endl;

swap_ranges(vec1.begin(), vec1.end(), deq1.begin());

cout<<"\nAfter the swap_range(), vec1 vector data: ";

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

cout<<*vec1Iter1<<" ";

cout<<endl;

cout<<"\nAfter the swap_range() deq1 deque data: ";

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

cout<<*deq1Iter<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

vec1 vector data: 10 11 12 13 14 15

deq1 deque data: 24 25 26 27 28 29

After the swap_range(), vec1 vector data: 24 25 26 27 28 29

After the swap_range() deq1 deque data: 10 11 12 13 14 15

Press any key to continue . . .

 

 

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