Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

PrevUpHomeNext

find_not

The header file 'find_not.hpp' contains a variants of a the stl algorithm find. The algorithm finds the first value in the given sequence that is not equal to the given value.

Consider this use of find():

auto std::vector<int> vec = { 1, 1, 2 };
auto it = std::find(vec.begin(), vec.end(), 1);

This gives us the first occurance of 1 in vec. What if we want to find the first occurrance of any number besides 1 in vec? We have to write an unfortunate amount of code:

auto std::vector<int> vec = { 1, 1, 2 };
auto it = std::find_if(vec.begin(), vec.end(), [](int i) { return i != 1; });

With find_not() the code gets much more terse:

auto std::vector<int> vec = { 1, 1, 2 };
auto it = find_not(vec.begin(), vec.end(), 1);

The existing find variants are: find(), find_if(), and find_if_not(). It seems natural to also have find_not(), for the very reason that we have find_if_not() -- to avoid having to write a lambda to wrap the negation of the find condition.

interface
template<typename InputIter, typename Sentinel, typename T>
InputIter find_not(InputIter first, Sentinel last, const T & x);

template<typename Range, typename T>
boost::range_iterator<Range> find_not(Range & r, const T & x);

These overloads of find_not return the first value that is not equal to x in the sequence [first, last) or r, respectively.

Examples

Given the container c1 containing { 0, 1, 2 }, then

find_not ( c1.begin(),     c1.end(),    1 ) --> c1.begin()
find_not ( c1.begin(),     c1.end(),    0 ) --> std::next(c1.begin())
Iterator Requirements

find_not works on all iterators except output iterators.

The template parameter Sentinel is allowed to be different from InputIter, or they may be the same. For an InputIter it and a Sentinel end, it == end and it != end must be well-formed expressions.

Complexity

Linear.

Exception Safety

find_not takes its parameters by value and do not depend upon any global state. Therefore, it provides the strong exception guarantee.

Notes

constexpr in C++14 or later.


PrevUpHomeNext