Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::rotate — cyclically rearrange a range

std::rotate from <algorithm> rearranges a range in place: the part starting at middle moves before the part starting at first. It preserves order within both parts and returns an iterator to their new boundary.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <algorithm>
template<class ForwardIterator>
constexpr ForwardIterator rotate(ForwardIterator first, ForwardIterator middle, ForwardIterator last);

std::rotate(first, middle, last) left-rotates [first, last): it exchanges the order of [first, middle) and [middle, last), preserving element order within each part. It removes nothing; when the second part is nonempty, the element at middle becomes first.

Both parts must be valid ranges. The operation needs mutable iterators meeting at least the forward iterator requirements, swappable elements, and support for move construction and move assignment. An input iterator alone is insufficient. The algorithm performs at most as many swaps as there are elements in the whole range.

The result marks the boundary between the relocated second part and the first part: its distance from first equals the original length of [middle, last). The specification's notation first + (last - middle) describes that position; it does not require random-access iterators. If first == middle, the result is last; if middle == last, the result is first. Both cases leave the sequence unchanged.

The example rotates five numbers left by two positions and prints the returned boundary's index. The non-policy overload discussed here is available in C++23. The cited working draft is a living document, not a frozen C++23 edition.

Examples

#include <algorithm>
#include <array>
#include <cstddef>
#include <iostream>
#include <iterator>

int main() {
    std::array<int, 5> values{1, 2, 3, 4, 5};
    auto boundary = std::rotate(values.begin(), values.begin() + 2, values.end());

    for (std::size_t i = 0; i < values.size(); ++i) {
        if (i != 0) std::cout << ' ';
        std::cout << values[i];
    }
    std::cout << '\n';
    std::cout << "boundary index: "
              << std::distance(values.begin(), boundary) << '\n';
}

Result

3 4 5 1 2
boundary index: 3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources