C++ Basics: Build a Cyclic View Starting at a Chosen Entry
Use std::rotate_copy to materialize a cyclic ordering without rearranging the source queue.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. You need a C++20-capable compiler and standard-library development headers, with g++ on PATH, plus 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 1Run the example
Save this as rotate-copy-cyclic-report-demo.cpp:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> queue{10, 20, 30, 40};
std::vector<int> report;
std::rotate_copy(queue.begin(), queue.begin() + 2, queue.end(),
std::back_inserter(report));
std::cout << "report:";
for (int id : report) std::cout << ' ' << id;
std::cout << '\n';
std::cout << "source first: " << queue.front() << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic rotate-copy-cyclic-report-demo.cpp -o rotate-copy-cyclic-report-demo &&
./rotate-copy-cyclic-report-demoObserved output:
report: 30 40 10 20
source first: 10Read the result
The chosen entry 30 becomes first, followed by 40 and then the old prefix 10, 20. The queue itself still begins at 10.
Apply it carefully
The middle iterator must lie within the input range, including its endpoints. Validate a user-provided offset before forming begin plus offset. Choosing begin or end produces the original ordering. Keep the output separate from the input and provide sufficient capacity through existing elements or an insertion iterator. Rotation preserves relative order within each of the two segments; it does not sort.
The C++ working draft describes the relevant rules. This example uses C++20; the current working draft also includes later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- rotate-copy-cyclic-report-demo.cpp rotate-copy-cyclic-report-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.