Another C++ STL algorithm, rotate() 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: Another example on 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)
{
// vector and deque containers
vector <int> vec1;
deque <int> deq1;
// vector and deque iterators
vector <int>::iterator vec1Iter1;
deque<int>::iterator deq1Iter1;
int i, j, k=1;
// push data into the vector and deque
for(i = -4; i <= 4; i++)
vec1.push_back(i);
for(j = -3; j <= 3; j++)
deq1.push_back(j);
// print content of Twister
cout<<"vec1 vector data is: ";
for(vec1Iter1 = vec1.begin(); vec1Iter1 != vec1.end(); vec1Iter1++)
cout<<*vec1Iter1 <<" ";
cout<<endl;
// let rotates...
rotate(vec1.begin(), vec1.begin() + 3, vec1.end());
cout<<"\nAfter rotating, vec1 vector data is: ";
for(vec1Iter1 = vec1.begin(); vec1Iter1 != vec1.end(); vec1Iter1++)
cout<<*vec1Iter1<<" ";
cout<<endl;
cout<<"\nThe original deq1 deque is: ";
for(deq1Iter1 = deq1.begin(); deq1Iter1 != deq1.end(); deq1Iter1++)
cout<<*deq1Iter1<<" ";
cout<<endl;
// let rotates
while(k <= deq1.end() - deq1.begin())
{
rotate(deq1.begin(), deq1.begin() + 1, deq1.end());
cout<<"\nRotation of a single deque element to the back, deq1 deque is: ";
for(deq1Iter1 = deq1.begin(); deq1Iter1 != deq1.end(); deq1Iter1++)
cout<<*deq1Iter1<<" ";
cout<<endl;
k++;
}
return 0;
}
Output examples:
vec1 vector data is: -4 -3 -2 -1 0 1 2 3 4
After rotating, vec1 vector data is: -1 0 1 2 3 4 -4 -3 -2
The original deq1 deque is: -3 -2 -1 0 1 2 3
Rotation of a single deque element to the back, deq1 deque is: -2 -1 0 1 2 3 -3
Rotation of a single deque element to the back, deq1 deque is: -1 0 1 2 3 -3 -2
Rotation of a single deque element to the back, deq1 deque is: 0 1 2 3 -3 -2 -1
Rotation of a single deque element to the back, deq1 deque is: 1 2 3 -3 -2 -1 0
Rotation of a single deque element to the back, deq1 deque is: 2 3 -3 -2 -1 0 1
Rotation of a single deque element to the back, deq1 deque is: 3 -3 -2 -1 0 1 2
Rotation of a single deque element to the back, deq1 deque is: -3 -2 -1 0 1 2 3
Press any key to continue . . .