std::rotate

From Cppreference

Jump to: navigation, search
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 );
(pre-C++11 version)

(C++11 version)

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) (pre-C++11 version)
The iterator equal to first + (last - n_first) (C++11 version)

[edit] Complexity

linear in the distance between first and last

[edit] Equivalent function

[edit] Example

The following code is an implementation of insertion sort in C++

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

Output:

before: 2 4 2 0 5 10 7 3 7 1
after:  0 1 2 2 3 4 5 7 7 10

[edit] See also

rotate_copy
copies and rotate a range of elements
(function template)