Namespaces
Variants
Views
Actions

std::rotate

From cppreference.com
 
 
 
Defined in header <algorithm>
template< class ForwardIterator >

void rotate( ForwardIterator first, ForwardIterator n_first, ForwardIterator last );
template< class ForwardIterator >

ForwardIterator rotate( ForwardIterator first, ForwardIterator n_first, ForwardIterator last );
(until C++11)

(since C++11)

Swaps the elements in the range [first, last) in such a way, that the element n_first becomes the first element of the new range and n_first - 1 becomes the last element.

Contents

[edit] Parameters

first, last - the range of elements to rotate
n_first - the element to move to the beginning of the new range

[edit] Return value

(none) (until C++11)
The iterator equal to first + (last - n_first) (since C++11)

[edit] Complexity

linear in the distance between first and last

[edit] Possible implementation

[edit] Example

std::rotate is a common building block in many algorithms. This example demonstrates insertion sort in C++

#include <vector>
#include <iostream>
#include <algorithm>
 
int main()
{
    std::vector<int> v{2, 4, 2, 0, 5, 10, 7, 3, 7, 1}; 
 
    std::cout << "before sort:      ";
    for(int n: v)
        std::cout << n << ' ';
    std::cout << '\n';
 
    // insertion sort
    for (auto i = v.begin(); i != v.end(); ++i) {
        std::rotate(std::upper_bound(v.begin(), i, *i), i, i+1);
    }
 
    std::cout << "after sort:       ";
    for(int n: v)
        std::cout << n << ' ';
    std::cout << '\n';
 
    // simple rotation
    std::rotate(v.begin(), v.begin() + 2, v.end());
 
    std::cout << "simple rotation : ";
    for(int n: v)
        std::cout << n << ' ';
    std::cout << '\n';
 
}

Output:

before sort:      2 4 2 0 5 10 7 3 7 1 
after sort:       0 1 2 2 3 4 5 7 7 10 
simple rotation : 2 2 3 4 5 7 7 10 0 1

[edit] See also

copies and rotate a range of elements
(function template) [edit]