C++ STL vector algorithm, rotate_copy(), string 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_copy () to exchange the elements in two adjacent ranges within a source range and copies the result to a destination range in C++ programming
To show: How to use the C++ algorithm, rotate_copy() to exchange the elements in two adjacent ranges within a source range and copies the result to a destination range in C++ programming
// rotate_copy(), string example
// compile with: /EHsc
// Illustrates how to use the rotate_copy() function.
//
// function:
// rotate_copy() - Rotate a sequence by n positions, copy the results to another same sized sequence.
//
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std;
int main(void)
{
// define a template class vector of strings
typedef vector<string> StrVector;
// define an iterator for template class vector of strings using typedef to simplify the code/name
typedef StrVector::iterator StrVectorIt;
StrVector Twister(8);
StrVector Rotated_Twister(8);
StrVectorIt start, middle, end, it, RTstart, RTend;
// location of first element of Twister
start = Twister.begin();
// one past the location last element of Twister
end = Twister.end();
// start position for rotating elements
middle = start + 3;
// location of first element of Rotated_Twister
RTstart = Rotated_Twister.begin();
// one past the location last element of Rotated_Twister
RTend = Rotated_Twister.end();
// initialize vector Twister with strings
Twister[0] = "she";
Twister[1] = "sells";
Twister[2] = "sea";
Twister[3] = "shells";
Twister[4] = "by";
Twister[5] = "the";
Twister[6] = "sea";
Twister[7] = "shore";
cout<<"Before calling rotate_copy(): "<<endl;
// print content of Twister
cout<<"Try this Twister:";
for (it = start; it != end; it++)
cout<<" "<<*it;
// rotate the items in the vector Twister to the right by 3 positions and copy the results to Rotated_Twister
rotate_copy(start, middle, end, RTstart);
cout<<endl<<"After calling rotate_copy():"<<endl ;
// print content of Twister
cout<<"Twister: ";
for (it = start; it != end; it++)
cout<<" "<<*it;
// print content of rotated Twister
cout<<endl<<"However the rotated Twister: ";
for (it = RTstart; it != RTend; it++)
cout<<" "<<*it;
cout<<endl;
return 0;
}
Output examples:
Before calling rotate_copy():
Try this Twister: she sells sea shells by the sea shore
After calling rotate_copy():
Twister: she sells sea shells by the sea shore
However the rotated Twister: shells by the sea shore she sells sea
Press any key to continue . . .