Check if there's exactly one match in a vector The challenge is to iterate over the vector only once and return the value within the range of the zero. However, if there are no matches or more than 1 match, deliver an error. The vector is unsorted and has no guarantee on it's size or the range of data.
More technically, the number of data accesses into the vector can't exceed N + 1 (access to iterators doesn't count)

I did this with a simple loop with 2 nested checks, and was wondering if there was a stdlib based or a better algorithmic solution that I'm not able to find.

Maybe ranges can help, but I'm limited to c++17 here, though the only c++17 feature I'm using is std::optional for error handling.

#include &lt;optional&gt;
#include &lt;vector&gt;

std::optional&lt;int&gt; get_unambiguous(const std::vector&lt;int&gt; &amp;data,
                                    const int range,
                                    const int zero = 0)
{
    std::optional&lt;int&gt; found;
    for (const auto&amp; item: data)
    {
        if (std::abs(item - zero) &lt; range) {
            if (found) {
                return {};
            }
            found = item;
        }
    }
    return found;
}
The standard library find functions return the .end() iterator for the container if they fail to find anything. We could follow the same convention, instead of using std::optional.

Rather than nesting the checks, we could split it into two separate loops, and use  std::find_if from the &lt;algorithm&gt; header, something like this:

auto const is_in_range = [&amp;] (int item) { return std::abs(item - zero) &lt; range; };

auto const first = std::find_if(data.begin(), data.end(), is_in_range);

if (first == data.end())
    return data.end(); // found nothing

auto const second = std::find_if(std::next(first), data.end(), is_in_range);

if (second != data.end())
    return data.end(); // found a second entry

return first;