Skip to content
C++ Basics: Rotate a Task List Without Losing Its Order

C++ Basics: Rotate a Task List Without Losing Its Order

November 4, 2026

Move the first two tasks to the end with std::rotate and inspect its return iterator.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as rotate-task-order-demo.cpp:

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

int main()
{
    std::vector<int> tasks{10, 20, 30, 40, 50};
    const auto old_first = std::rotate(tasks.begin(), tasks.begin() + 2, tasks.end());
    std::cout << "Tasks:";
    for (int task : tasks) std::cout << ' ' << task;
    std::cout << "\nOld first: " << *old_first << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic rotate-task-order-demo.cpp -o rotate-task-order-demo &&
./rotate-task-order-demo

Observed output:

Tasks: 30 40 50 10 20
Old first: 10

Read the result

The task at the chosen middle becomes the first element. Both groups retain their internal order: 30, 40, 50 precede 10, 20. The returned iterator identifies the new position of the original first element. The vector still has five elements.

Apply it carefully

The middle iterator must belong to the same range, including its endpoints. Validate a user-supplied offset before adding it to begin(). Do not dereference the returned iterator when it equals end(), which can happen when middle equals begin(). Rotation changes values at positions; it does not create a new container or guarantee that an iterator still names the same logical task.

The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- rotate-task-order-demo.cpp rotate-task-order-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on