Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the standard library have find and find_if?

Tags:

c++

std

stl

Couldn't find_if just be an overload of find? That's how std::binary_search and friends do it...

like image 302
Billy ONeal Avatar asked Aug 20 '10 17:08

Billy ONeal


1 Answers

A predicate is a valid thing to find, so you could arrive at ambiguities.


Consider find_if is renamed find, then you have:

template <typename InputIterator, typename T>
InputIterator find(InputIterator first, InputIterator last, const T& value);

template <typename InputIterator, typename Predicate>
InputIterator find(InputIterator first, InputIterator last, Predicate pred);

What shall be done, then, with:

find(c.begin(), c.end(), x); // am I finding x, or using x to find?

Rather than try to come up with some convoluted solution to differentiate based on x (which can't always be done*), it's easier just to separate them.

*This would be ambiguous, no matter what your scheme is or how powerful it might be†:

struct foo
{
    template <typename T>
    bool operator()(const T&);
};

bool operator==(const foo&, const foo&);

std::vector<foo> v = /* ... */;
foo f = /* ... */; 

// f can be used both as a value and as a predicate
find(v.begin(), v.end(), f); 

†Save mind reading.

like image 124
GManNickG Avatar answered Sep 18 '22 18:09

GManNickG