Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

rotate_copy
c++
communitycreator

How to use the rotate_copy() function in C++

Harsh Jain

What is the rotate_copy() function?

The rotate_copy() function in C++ is used to rotate the order of the elements within a specified range.

After rotation, the element pointed to by middle now becomes the first element, and then copies the new rotated vector to a new result vector.

In other words, the rotation happens at the iterator pointing to the middle element.


Here, middle does not mean the middle-most element in the array. It means any elements present within the range at which we want to rotate the elements.


This function is available in the <algorithm.h> header file.

Parameters

The rotate_copy() function accepts the following parameters:

  • first: This is an iterator that points to the first index of the array or vector from where we want to rotate the elements.

  • middle: This is an iterator that points to the element of the array or vector at which the rotation will be performed, and this element now comes at the start of the array.

  • last: This is an iterator that points to the last index of the array or vector to where we want to rotate the elements.

  • result: This is an iterator that points to the new array or vector to where we want to store the rotated vector. The size of the result should be large enough to accommodate the elements in the range [first, last).

Returns

The rotate_copy() function returns an iterator that points to the end of the result where last the element has been copied from the new rotated vector.

Code

Let’s look at the code now to understand it better.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
  vector<int> vec = {1,2,3,4,5,6,7,8,9};
  vector<int> result (9);

  rotate_copy(vec.begin(), vec.begin() + 3, vec.end(), result.begin());
  cout << "Result vector: ";
  for (int x: result)
    cout << x << " ";

  return 0;
}
Use rotated_copy() function in C++

Explanation:

  • From lines 1 to 3, we import the required header files.

  • In line 7, we create a vector containing integer values.

  • In line 8, we create the vector where we want to store the rotated elements from the vector.

  • In line 10, we call the rotate_copy() function and pass the required parameters. We can see that we specified that we want to rotate the elements in the vector at index 3 and store them in the result vector.

  • Finally, from lines 11 to 13, we print the rotated vector.

So, in this way, we can perform a rotation of elements and copy them into another vector easily in C++.

RELATED TAGS

rotate_copy
c++
communitycreator
RELATED COURSES

View all Courses

Keep Exploring