Skip to content
C++ Basics: Copy the Smallest Values into a Fixed Buffer

C++ Basics: Copy the Smallest Values into a Fixed Buffer

November 4, 2026

Use std::partial_sort_copy to select a sorted prefix without modifying the source.

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 partial-sort-copy-smallest-demo.cpp:

#include <algorithm>
#include <array>
#include <iostream>

int main()
{
    const std::array<int, 5> durations{12, 3, 9, 1, 7};
    std::array<int, 3> fastest{};
    const auto written_end = std::partial_sort_copy(
        durations.begin(), durations.end(), fastest.begin(), fastest.end());
    std::cout << "Fastest:";
    for (auto it = fastest.begin(); it != written_end; ++it) std::cout << ' ' << *it;
    std::cout << "\nSource first: " << durations.front() << '\n';
}

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

g++ -std=c++20 -Wall -Wextra -Werror -pedantic partial-sort-copy-smallest-demo.cpp -o partial-sort-copy-smallest-demo &&
./partial-sort-copy-smallest-demo

Observed output:

Fastest: 1 3 7
Source first: 12

Read the result

The three-element destination receives 1, 3, 7 in sorted order. The source still begins with 12. The return iterator marks the end of the values actually copied, which matters when the input has fewer elements than the destination.

Apply it carefully

The output must contain writable elements, not just reserved capacity, and must not overlap the input. This array provides exactly three initialized slots. Iterate only to written_end; unused destination slots are not selected results. A custom descending comparator instead selects the largest values. Selection copies values, so this pattern is unsuitable for types that cannot be copied into the output.

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 -- partial-sort-copy-smallest-demo.cpp partial-sort-copy-smallest-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