为什么标准库有find和find_if? [英] Why does the standard library have find and find_if?
本文介绍了为什么标准库有find和find_if?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无法 find_if
只是重载 find
?这是 std :: binary_search
和朋友做的方法
Couldn't find_if
just be an overload of find
? That's how std::binary_search
and friends do it...
推荐答案
考虑 find_if
已重命名为 find
,则您有:
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);
接下来应该做什么:
find(c.begin(), c.end(), x); // am I finding x, or using x to find?
而不是试图提出一些复杂的解决方案来区分基于 x
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);
†保存心态阅读。
这篇关于为什么标准库有find和find_if?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文