C++ Basics: Exchange Two Prefixes Without Overrunning Either Range
Use C++20 std::ranges::swap_ranges when two buffers may have different lengths. The bounded overload exchanges only paired entries.
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 swap-ranges-shorter-input-demo.cpp:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<int> left{1, 2, 3};
std::vector<int> right{8, 9};
auto result = std::ranges::swap_ranges(left, right);
std::cout << "left:";
for (int value : left) std::cout << ' ' << value;
std::cout << "\nright:";
for (int value : right) std::cout << ' ' << value;
std::cout << "\nexchanged: " << result.in1 - left.begin() << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic swap-ranges-shorter-input-demo.cpp -o swap-ranges-shorter-input-demo &&
./swap-ranges-shorter-input-demoObserved output:
left: 8 9 3
right: 1 2
exchanged: 2Read the result
Two pairs are exchanged. The third entry of left remains 3, and the returned iterator reports the consumed prefix length.
Apply it carefully
This operation swaps elements, not whole containers: neither vector changes size. Use a container swap when ownership of the entire sequence should exchange. The ranges must not overlap, and their elements must be swappable. If equal lengths are required by your application, validate that separately rather than accepting a partial exchange.
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 -- swap-ranges-shorter-input-demo.cpp swap-ranges-shorter-input-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.