C++ Logo

std-proposals

Advanced search

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

From: Kosher Yosher <goekhan.oezdogan_at_[hidden]>
Date: Thu, 1 Oct 2020 16:42:53 +0100
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;
}

Received on 2020-10-01 10:43:07