c++ - std::find 的优点

标签 c++ c++11 stl find containers

与容器的 find 方法相比,使用 C++11 的 std::find 有什么优势吗?

  • std::vector 的情况下(没有 find 方法)std::find 使用一些智能算法或简单地迭代每个元素的天真方法?

  • std::map 的情况下,您似乎需要传递一个 std::pair,即 value_typestd::map 的。这似乎不是很有用,因为通常您希望查找键或映射元素。

  • std::liststd::setstd::unordered_set 等其他容器呢?

最佳答案

In the case of std::vector (which does not have a find method) does std::find use some smart algorithm or the naive way of simply iterating over every element?

它不能,因为 vector 没有排序。除了具有 O(n) 复杂度的线性搜索之外,没有其他方法可以在未排序的 vector 中找到元素。

另一方面,序列容器不提供 find() 成员函数,因此您不可能使用它。

In the case of std::map it seems you need to pass along an std::pair, which is the value_type of an std::map. This does not seem very useful as usually you'd want to find for either a key or a mapped element.

的确,这里您应该使用find() 成员函数,它保证了更好的复杂度(O(log N))。

一般来说,当一个容器暴露一个与泛型算法同名的成员函数时,这是因为该成员函数做同样的事情,但提供了更好的复杂性保证。

What about other containers like std::list or std::set or std::unordered_set ?

就像 std::vector 一样,std::list 不是排序的容器 - 所以同样的结论适用。

对于 std::setstd::unordered_set,您应该使用 find() 成员函数,它保证更好的复杂性(分别为 O(log n) 和平均 O(1))。

关于c++ - std::find 的优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17256001/

相关文章:

c# - 使用 COM 互操作从非托管代码调用托管委托(delegate)

c++ - 'grp' 未在此范围内声明,

c++ - 为什么别名模板会给出冲突的声明?

c++ - 要导出的 Base unique_ptr vector

c++ - 如何在 C++ 中创建一个基本线程

c++ - RAII 的有用性无一异常(exception)

c++ - 绑定(bind)到引用时临时对象生命周期扩展异常的基本原理是什么?

使用模板的 C++ 11 异步编程

c++ - PImpl 并不能使我免于导出 STL

c++ - 从 std::set C++ 中删除重复项