Skip to content
C++ Basics: Show Reverse Order Without Mutating the Source

C++ Basics: Show Reverse Order Without Mutating the Source

November 9, 2026

Use std::reverse_copy to create a reverse-ordered report while keeping the original event sequence intact.

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 1

Run the example

Save this as reverse-copy-report-order-demo.cpp:

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

int main()
{
    std::vector<int> chronological{101, 102, 103};
    std::vector<int> newest_first;
    std::reverse_copy(chronological.begin(), chronological.end(),
                      std::back_inserter(newest_first));
    std::cout << "report:";
    for (int id : newest_first) std::cout << ' ' << id;
    std::cout << '\n';
    std::cout << "source first: " << chronological.front() << '\n';
}

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

g++ -std=c++20 -Wall -Wextra -Werror -pedantic reverse-copy-report-order-demo.cpp -o reverse-copy-report-order-demo &&
./reverse-copy-report-order-demo

Observed output:

report: 103 102 101
source first: 101

Read the result

The report starts with 103, while the source still starts with 101. Reversal is based on position, not a numeric sort.

Apply it carefully

Use separate destination storage: reverse_copy requires nonoverlapping input and output ranges. If you only need to print or inspect the reverse order, reverse iterators can avoid the extra collection. If the source itself should change, reverse performs an in-place reversal. This example knows the source is nonempty before calling front; arbitrary inputs need an emptiness check.

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 -- reverse-copy-report-order-demo.cpp reverse-copy-report-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