find 被设计为一种通用算法,适用于各种容器(甚至包括那些可能在标准库之外的容器) . 它's also designed to do simply more than return whether an element was found or not -- it returns an iterator pointing to the item if found. As a result, it doesn'如果找不到元素,则返回null或类似的东西 . 它返回迭代器 .
/// @return True if `val` is found in `[first, last)`
template <class Iterator, class Element>
bool contains(Iterator first, Iterator last, const Element& val)
{
return std::find(first, last, val) != last;
}
...
if (contains(vector.begin(), vector.end(), item))
do_this();
else
do_that();
3 回答
将返回一个迭代器,所以通过比较它
您实际上正在检查是否存在具有该项的此类迭代器 .
find
未能找到匹配的结果是指向所提供范围末尾的迭代器,并且没有什么特别关于允许它们像布尔状态进行比较的结束迭代器 .find
被设计为一种通用算法,适用于各种容器(甚至包括那些可能在标准库之外的容器) . 它's also designed to do simply more than return whether an element was found or not -- it returns an iterator pointing to the item if found. As a result, it doesn'如果找不到元素,则返回null或类似的东西 . 它返回迭代器 .如果你真的做了很多这样的事情(我建议你做这样的事情,因为你在日常代码中引入了一些异类),你可以这样做:
它正在检查是否实际找到了该值 .
std::find() 将迭代器返回到查询范围中的第一个元素 .
如果返回的值等于 vector.end() ,则表示它未找到该项 .
有关更多信息,请参见this .