4 Comments

I love the projection thing in ranges. Once you get used to it (reading/writing the code) it's really nice.

Expand full comment

It's such a simple idea, yet so powerful. I just wish taking addresses of standard functions or member functions wasn't UB.

Expand full comment

What does the `{}` in the line `auto it = std::ranges::min_element(elements, {}, &Element::v);` refer to?

The documentation states "comparison to apply to the projected elements", however, as a newbie, that is like a foreign language to me.

Ref: https://en.cppreference.com/w/cpp/algorithm/ranges/min_element

Expand full comment

There are two parts to this:

- Comp = ranges::less in the template

- Comp comp = {} in the function signature

Since both the template and the function argument have default values, the comparator will be std::ranges::less{} unless it is specified in the call.

Now in the example, we are specifying the projection, which comes after, so we need to give the comparator some value and if we want the default we could either spell it out as std::ranges::less{} or let the type deduction machinery do its job and only say {}, which will figure the type from the default template argument.

Notably, if you would call std::min_element(rng, std::ranges::greater{}); you would actually get max (although not necessarily symmetrically, we are still processing left-to-right, so equivalent elements can make it asymmetrical).

Expand full comment