C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Ranges algorithms should prioritize container defined algorithms

From: Barry Revzin <barry.revzin_at_[hidden]>
Date: Tue, 15 Oct 2024 20:21:20 -0500
On Tue, Oct 15, 2024 at 8:05 PM Anton Petushkov via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hi,
>
> Currently, the ranges methods provided in <ranges> first check to see if
> the range passed in has a user defined method (i.e. std::ranges::size(cont)
> first checks if cont.size() is valid, and if so, returns that). I
> think ranges algorithms provided in <algorithm> should also first check for
> signature compatible, class defined methods.
>
> An example of where this is important is with ranges::[lower/upper]_bound.
> First, if the input range has a defined lower_bound method, it is likely
> the intended way to interface with the class. Second, this would allow
> standard library containers such as std::map and std::set to be used
> efficiently in these algorithms.
>
> Another example would be if you're passing a string into ranges::find(),
> you'd likely want the algorithm to use the find() method in the string
> class rather than the naive std::ranges implementation.
>
> Please let me know your thoughts!
> Anton
>

The problem is these algorithms don't necessarily do the same thing.

std::set<T>::find is doing a search based on <, while std::find is doing a
search based on == (either can have the predicate customized). Those can
actually find different elements. std::map<K, V>::find is looking by K, but
std::find would look by std::pair<K, V>. Those aren't even the same type.
So a naive "just use the member" approach won't work. There would need to
be some kind of opt-in by the containers.

The other fun one is std::list<T>::sort, where neither container/iterators
don't meet the constraints of the algorithm. And yet it exists.

Barry

Received on 2024-10-16 01:21:33