简体   繁体   English

搜索std :: set的最佳方法

[英]Optimal way to search a std::set

How should one search a std::set, when speed is the critical criterion for his/her project? 当速度是他/她项目的关键标准时,如何搜索std :: set?

set:find ? 设置:找到

Complexity: 复杂:

Logarithmic in size. 对数大小。

std::binary_search ? std :: binary_search

Complexity: 复杂:

On average, logarithmic in the distance between first and last: Performs approximately log2(N)+2 element comparisons (where N is this distance). 平均而言,第一个和最后一个距离的对数:执行近似log2(N)+2个元素比较(其中N是此距离)。 On non-random-access iterators, the iterator advances produce themselves an additional linear complexity in N on average. 在非随机访问迭代器上,迭代器的进展产生了N平均额外的线性复杂度。

Just a binary search implemented by him/her (like this one)? 只是他/她实施的二元搜索(就像这个 )? Or the STL's one is good enough? 或者STL的足够好?

Is there a way to answer this theoretically? 有没有办法在理论上回答这个问题? Or we have to test ourselves? 或者我们要测试自己? If someone has, it would be nice if (s)he would share this information with us (if no, we are not lazy :) ). 如果有人,如果他会与我们分享这些信息会很好(如果不是,我们不会懒惰:))。

The iterator type provided by std::set is a bidirectional_iterator , a category which does not require random access to elements, but only element-wise movements in both directions. std::set提供的迭代器类型是一个bidirectional_iterator ,这个类别不需要随机访问元素,但只能在两个方向上进行逐元素移动。 All random_access_iterator 's are bidirectional_iterator s, but not vice versa. 所有random_access_iterator的是bidirectional_iterator S,而不是相反。

Using std::binary_search on a std::set can therefore yield O(n) runtime as per the remarks you quoted, while std::set::find has guaranteed O(logn) . 因此,在std::set上使用std::binary_search可以根据引用的备注产生O(n)运行时,而std::set::find保证O(logn)

So to search a set , use set::find . 所以要搜索一个set ,请使用set::find

It's unlikely that std::set has a random access iterator. std::set不太可能有随机访问迭代器。 Even if it did, std::binary_search would access at least as many nodes as .find , since .find accesses only the ancestors of the target node. 即使它确实如此, std::binary_search也将访问至少与.find一样多的节点,因为.find只访问目标节点的祖先。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM