C++ STL algorithm, rotate() 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 C++ rotate() to exchange the elements in two adjacent ranges in C++ programming

To show: How to use the C++ algorithm, rotate() to exchange the elements in two adjacent ranges in C++ programming

 

// C++ STL algorithm, rotate()

#include <vector>

#include <deque>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// containers

vector <int> v1;

deque <int> d1;

 

// iterators for containers

vector <int>::iterator v1Iter1;

deque<int>::iterator d1Iter1;

int i, j, k = 1;

 

// pushing data into the containers

for (i = -3; i <= 5; i++)

{

v1.push_back(i);

}

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

{

d1.push_back(j);

}

 

// print the data

cout<<"\nv1 vector is: ";

for (v1Iter1 = v1.begin(); v1Iter1 != v1.end(); v1Iter1++)

cout<<*v1Iter1<<" ";

cout<<endl;

rotate(v1.begin(), v1.begin() + 3, v1.end());

cout<<"\nAfter rotating, v1 vector is: ";

for (v1Iter1 = v1.begin(); v1Iter1 != v1.end(); v1Iter1++)

cout<<*v1Iter1<<" ";

cout<<endl;

cout<<"\nThe original d1 deque is: ";

for (d1Iter1 = d1.begin(); d1Iter1 != d1.end(); d1Iter1++)

cout<<*d1Iter1<<" ";

cout<<endl;

while (k <= d1.end() - d1.begin())

{

rotate(d1.begin(), d1.begin() + 1, d1.end());

cout<<"\nAfter the rotation of a single deque element to the back, d1 deque is: ";

for (d1Iter1 = d1.begin(); d1Iter1 != d1.end(); d1Iter1++)

cout<<*d1Iter1<<" ";

cout<<endl;

k++;

}

return 0;

}

 

Output examples:

 

v1 vector is: -3 -2 -1 0 1 2 3 4 5

After rotating, v1 vector is: 0 1 2 3 4 5 -3 -2 -1

The original d1 deque is: 0 1 2 3 4 5

After the rotation of a single deque element to the back, d1 deque is: 1 2 3 4 5 0

After the rotation of a single deque element to the back, d1 deque is: 2 3 4 5 0 1

After the rotation of a single deque element to the back, d1 deque is: 3 4 5 0 1 2

After the rotation of a single deque element to the back, d1 deque is: 4 5 0 1 2 3

After the rotation of a single deque element to the back, d1 deque is: 5 0 1 2 3 4

After the rotation of a single deque element to the back, d1 deque is: 0 1 2 3 4 5

Press any key to continue . . .

 

 

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