C++ Logo

std-proposals

Advanced search

Re: Finding the index of an element (std::find_first_index)

From: Ivan Matek <libbooze_at_[hidden]>
Date: Sun, 4 Oct 2020 16:18:57 +0200
This is very useful, but I doubt that you will be able to get it into the
standard.
People in standardization are usually not that concerned with usability(
aka != .end() spam).
You might want to get it into boost, Marshall might be more receptive.

More controversial discussion regarding your algorithm is:

should it return std::optional<size_t> ?

On Thu, Oct 1, 2020 at 5:43 PM Kosher Yosher via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hi,
>
> Quick thoughts on adding a new function to <algorithm> which returns the
> index of an element, matched by a predicate, in a container? The goal is to
> stop writing FindX scanning functions and make it as concise as possible to
> do this common operation.
>
> Example:
>
> auto i = std::find_first_index(v.begin(), v.end(), [](const auto& e){
> return e.someMember == 1337; });
> if (i != std::invalid_index)
> {
> // Do something with i.
> }
>
> Implementation:
>
> constexpr std::size_t invalid_index = std::numeric_limits<std::size_t>::max();
>
> template<class InputIterator, class UnaryPredicate>
> constexpr std::size_t find_first_index(InputIterator first, InputIterator last, UnaryPredicate pred)
> {
> std::size_t i = 0;
> while (first != last)
> {
> if (pred(*first))
> {
> return i;
> }
> ++first;
> ++i;
> } return std::invalid_index;
> }
>
> --
> Std-Proposals mailing list
> Std-Proposals_at_[hidden]
> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals
>

Received on 2020-10-04 09:19:10