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
std::ranges::sort(nums)orders ascending with no iterator pair in sight.- Passing
std::greater<>{}as the comparator flips the same call to descending. - A lambda comparing
a.size()tob.size()sorts the strings shortest first.
Keywords and builtins used here
constintreturnsort_bothvoid
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.
Step 1 of 3 in Algorithms, step 13 of 27 in Language basics.