Skip to content
C++ Basics: Sort Records with a Member Projection

C++ Basics: Sort Records with a Member Projection

November 7, 2026

A ranges sort projection selects the field to compare while the algorithm moves whole records into order.

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 ranges-sort-member-projection-demo.cpp:

#include <algorithm>
#include <array>
#include <functional>
#include <iostream>
#include <string_view>

struct Job {
    std::string_view name;
    int minutes;
};

int main()
{
    std::array<Job, 3> jobs{{{"backup", 30}, {"lint", 4}, {"build", 12}}};
    std::ranges::sort(jobs, std::ranges::less{}, &Job::minutes);
    for (const auto& job : jobs) {
        std::cout << job.name << ": " << job.minutes << '\n';
    }
}

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

g++ -std=c++20 -Wall -Wextra -Werror -pedantic ranges-sort-member-projection-demo.cpp -o ranges-sort-member-projection-demo &&
./ranges-sort-member-projection-demo

Observed output:

lint: 4
build: 12
backup: 30

Read the result

The output orders jobs by duration: lint, build, then backup. Names travel with their records; the projection does not extract and sort a separate list of integers.

Apply it carefully

The comparator acts on projected values and must define a strict weak ordering. Equal durations have no promised relative order with sort. Use stable_sort when preserving input order among ties matters. Projections simplify a single key; a tuple-returning projection can express multiple keys. This example uses the C++20 ranges overload.

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 -- ranges-sort-member-projection-demo.cpp ranges-sort-member-projection-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