C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] Finding the index of an element (std::find_first_index)
From: Arthur O'Dwyer (arthur.j.odwyer_at_[hidden])
Date: 2020-10-04 22:30:49


On Sun, Oct 4, 2020, 11:23 PM Barry Revzin <barry.revzin_at_[hidden]> wrote:

> On Sun, Oct 4, 2020 at 10:08 PM Arthur O'Dwyer via Std-Proposals <
> std-proposals_at_[hidden]> wrote:
>
>> Btw, I've been mostly convinced that this algorithm is not needed (not
>> even in theory) by the slightly handwavey example given earlier in this
>> thread, of composing it out of the `enumerate` view which has a decent
>> chance of getting into C++23. Here's the example worked out:
>> https://godbolt.org/z/YE4f7T
>>
>> template<class R, class Pred>
>> size_t find_index(R&& r, Pred pred)
>> {
>> auto e = ranges::views::enumerate(r);
>> auto getSecond = [](auto&& x) -> decltype(auto) { return (x.second); };
>> return (*std::ranges::find_if(e, pred, getSecond)).first;
>> }
>>
>> This is not elegant code *at all*, but at least it shows that it's
>> possible to get integer indices out of Ranges algorithms, if you really
>> need integers, and without doing two passes.
>>
>
> More straightforward to use take_while:
>
> template <typename R, typename Pred>
> auto count_while_not(R&& r, Pred&& pred) {
> return
> ranges::distance(r | ranges::views::take_while(std::not_fn(pred)));
> }
>

Is that guaranteed to do only the one traversal, though? I guess yes
because take_while is lazy?

Arthur

>



STD-PROPOSALS list run by std-proposals-owner@lists.isocpp.org

Standard Proposals Archives on Google Groups