Defined in header <algorithm> | ||||
---|---|---|---|---|
| (until C++11) | |||
| (since C++11) |
Performs a left rotation on a range of elements.
Specifically, std::rotate
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.
A precondition of this function is that [first, n_first)
and [n_first, last)
are valid ranges.
Parameters
first | - | the beginning of the original range |
n_first | - | the element that should appear at the beginning of the rotated range |
last | - | the end of the original range |
Type requirements | ||
- ForwardIt must meet the requirements of ValueSwappable and ForwardIterator . | ||
-The type of dereferenced ForwardIt must meet the requirements of MoveAssignable and MoveConstructible . |
Return value
(none). | (until C++11) |
The iterator equal to | (since C++11) |
Complexity
Linear in the distance between first
and last
.
Possible implementation
|
Example
std::rotate
is a common building block in many algorithms. This example demonstrates insertion sort:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #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 to the left std::rotate(v.begin(), v.begin() + 1, v.end()); std::cout << "simple rotate left : " ; for ( int n: v) std::cout << n << ' ' ; std::cout << '\n' ; // simple rotation to the right std::rotate(v.rbegin(), v.rbegin() + 1, v.rend()); std::cout << "simple rotate right : " ; for ( int n: v) std::cout << n << ' ' ; std::cout << '\n' ; } |
Output:
1 2 3 4 | 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 rotate left : 1 2 2 3 4 5 7 7 10 0 simple rotate right: 0 1 2 2 3 4 5 7 7 10 |
See also
copies and rotate a range of elements (function template) | |
std::experimental::parallel::rotate
(parallelism TS) | parallelized version of std::rotate (function template) |
Please login to continue.