为什么标准库有find和find_if?

Bil*_*eal 11 c++ stl std design-rationale

不能find_if只是一个超载find?那是怎么std::binary_search和朋友一起做的......

GMa*_*ckG 16

谓词是一个有用的东西,所以你可以得出歧义.


考虑find_if重命名find,然后你有:

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);
Run Code Online (Sandbox Code Playgroud)

那么,应该做什么:

find(c.begin(), c.end(), x); // am I finding x, or using x to find?
Run Code Online (Sandbox Code Playgroud)

而不是尝试提出一些基于x(不能总是做*)区分的复杂解决方案,将它们分开更容易.

*这将是模糊的,无论你的计划是什么或它有多强大†:

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); 
Run Code Online (Sandbox Code Playgroud)

†保存心灵阅读.