This C++ program demonstrates the rotate_copy() algorithm. The function rotate_copy() takes four iterators as parameters – first iterator to the beginning of container, second iterator to element by which the elements are rotated, third iterator to the end of the set of elements to be rotated and the fourth iterator to the starting of the container where rotated elements are to be stored. The program demonstrates the use of the algorithm which doesn’t modify the order of the container whose order is being rotated.
Here is the source code of the C++ program which demonstrates the rotate_copy() 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_copy() 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(1)
<< left << a[i] << " ";
}
cout << endl;
}
int main()
{
char s[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
int slen = sizeof(s) / sizeof(char), tlen = slen;
char t[tlen];
cout << "Character array s[] : ";
print(s, slen);
cout << "Rotate s[] with \'C\' as middle element and copy in t[]" << endl;
rotate_copy(s, s + 2, s + slen, t);
cout << "Character array t[] : ";
print(t, tlen);
cout << "Rotate t[] with \'A\' as middle element and copy in s[]" << endl;
rotate_copy(t, t + 6, t + tlen, s);
cout << "Character array s[] : ";
print(s, slen);
cout << "Character array t[] : ";
print(t, tlen);
}
$ a.out Character array s[] : 1. A 2. B 3. C 4. D 5. E 6. F 7. G 8. H Rotate s[] with 'C' as middle element and copy in t[] Character array t[] : 1. C 2. D 3. E 4. F 5. G 6. H 7. A 8. B Rotate t[] with 'A' as middle element and copy in s[] Character array s[] : 1. A 2. B 3. C 4. D 5. E 6. F 7. G 8. H Character array t[] : 1. C 2. D 3. E 4. F 5. G 6. H 7. A 8. B
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Practice Programming MCQs
- Check C++ Books
- Apply for C++ Internship
- Practice Computer Science MCQs
- Check Computer Science Books