Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 870
康桓瑋 Avatar asked Oct 23 '25 02:10

康桓瑋


1 Answers

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(); });
like image 185
Barry Avatar answered Oct 25 '25 15:10

Barry