C++ std::rotate

This is an interesting template function, defined in , which moves elements of a container class, much in the same way when you rotate the number wheel on a luggage combination lock: rotate the wheel to the left, all of the numbers move along with that rotation; rotate the wheel to the right
and the numbers do the same thing, but in the opposite motion.

Much like the arrow on the combination lock, the rotate’s second parameter, ForwardIt n_first, is the element that ends up being under the arrow.
By being under the arrow, we mean that ForwardIt n_first ends up at the front of the container, and the item immediately before it ends up at the end of the container.

Here’s an example of moving the metaphorical wheel, left then right:

#include <algorithm>
#include <iostream>
#include <vector>

void print_elements(std::vector<int> values);

/************************************************************************/
int main(int, char**)
{
  auto combination_lock = std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  print_elements(combination_lock);
  std::cout << " ################ \n";

  // Rotate our wheel to the left 5 positions
  std::rotate(combination_lock.begin(), combination_lock.begin() + 5, combination_lock.end());
  print_elements(combination_lock);
  std::cout << " ################ \n";

  // Rotate our wheel to the right 3 positions
  std::rotate(combination_lock.rbegin(), combination_lock.rbegin() + 3, combination_lock.rend());
  print_elements(combination_lock);
}

/************************************************************************/
void print_elements(std::vector<int> values)
{
  for (auto& val : values)
  {
    std::cout << val << "\n";
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *