This C++ program demonstrates the rotate() algorithm. The function rotate() takes three iterators as parameters – first iterator to the beginning of container, second iterator to element by which the elements are rotated and the third iterator to the end of the set of elements to be rotated. The program demonstrates the use of the algorithm which modifies the order of the container whose order is being rotated.
Here is the source code of the C++ program which demonstrates the rotate() algorithm. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ Program to rotate the order of elements using rotate() algorithm
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <iomanip>
using namespace std;
void print(char a[], int N)
{
for(int i = 0; i < N; i++)
{
cout << (i + 1) << ". " << setw(2)
<< left << a[i] << " ";
}
cout << endl;
}
int main()
{
char s[] = {'A', 'B', 'C', 'D', 'E', 'G', 'H'};
int slen = sizeof(s) / sizeof(char);
cout << "Original order : ";
print(s, slen);
cout << "Rotate with \'C\' as middle element" << endl;
rotate(s, s + 2, s + slen);
cout << "Rotated order : ";
print(s, slen);
cout << "Rotate with \'G\' as middle element" << endl;
rotate(s, s + 3, s + slen);
cout << "Rotated order : ";
print(s, slen);
cout << "Rotate with \'A\' as middle element" << endl;
rotate(s, s + 3, s + slen);
cout << "Original order : ";
print(s, slen);
}
$ a.out Original order : 1. A 2. B 3. C 4. D 5. E 6. G 7. H Rotate with 'C' as middle element Rotated order : 1. C 2. D 3. E 4. G 5. H 6. A 7. B Rotate with 'G' as middle element Rotated order : 1. G 2. H 3. A 4. B 5. C 6. D 7. E Rotate with 'A' as middle element Original order : 1. B 2. C 3. D 4. E 5. G 6. H 7. A
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
Related Posts:
- Check C++ Books
- Check Programming Books
- Apply for C++ Internship
- Practice Computer Science MCQs
- Apply for Computer Science Internship