typestar

Sorting with ranges in C++

C++20's std::ranges::sort takes the whole container and any ordering you hand it.

#include <algorithm>
#include <functional>
#include <string>
#include <vector>

void sort_both(std::vector<int>& nums, std::vector<std::string>& words) {
    std::ranges::sort(nums);
    std::ranges::sort(nums, std::greater<>{});  // descending
    std::ranges::sort(words, [](const std::string& a, const std::string& b) {
        return a.size() < b.size();
    });
}

How it works

  1. std::ranges::sort(nums) orders ascending with no iterator pair in sight.
  2. Passing std::greater<>{} as the comparator flips the same call to descending.
  3. A lambda comparing a.size() to b.size() sorts the strings shortest first.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
344
Tokens
118
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 101 seconds.

Type this snippet

Step 1 of 3 in Algorithms, step 13 of 27 in Language basics.

← Previous Next →