How to project elements nestedly in c++20 constrained algorithms?

350 Views Asked by At

Suppose I have a std::vector of std::pairs, then I can using c++20 constrained algorithm's projection facility to sort elements according to sub-object:

std::vector<std::pair<int, std::string>> v;
// sort by std::string
ranges::sort(v, {}, &std::pair<int, std::string>::second);

but how to do nested projection like this?

// sort by std::string::size
ranges::sort(v, {}, &std::pair<int, std::string>::second::size);
1

There are 1 best solutions below

0
On BEST ANSWER

The projection is just an arbitrary callable. Providing a pointer to member is convenient if that works. But if it doesn't, just use a lambda:

ranges::sort(v, ranges::less(), [](auto const& elem) { return elem.second.size(); });