c++ - unordered_set<int>::iterator it+n 的时间复杂度是多少?

标签 c++ time-complexity

假设我有一个 std::unordered_set<int>命名为 myset我想从 myset 返回一个随机数在O(1)时间。我首先使用 rand()生成一个随机数:

int n = rand() %  myset.size();

然后,我做:

myset.begin() + n;

我想知道 myset.begin() + nO(n)O(1)

谢谢!

最佳答案

std::unordered_set<>::iterator (结果来自 myset.begin() )是一个 Constant ForwardIterator . Ref

A ForwardIterator支持递增(++myIterator)但不支持随机递增,不像RandomAccessIterator .

因此myset.begin() + n不保证按标准编译。它不编译 here .

你可以做 ++增量n循环,但当然,复杂度至少为 O(n)。

关于c++ - unordered_set<int>::iterator it+n 的时间复杂度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45395619/

相关文章:

algorithm - 如何计算平均复杂度

algorithm - 为什么要考虑二分查找运行时间复杂度为log2N

c++ - 扩展阵列容量

c++ - 重载运算符>>

algorithm - Rabin Karp 算法中的 Spurious Hits 如何等于 O (n/q)?

算法复杂度 n*(m+n)^2

c++ - 如何使用 ULARGE_INTEGER 进行算术运算

c++ - 在 C++ 中使用 map 而不是 array 来保护在数组边界之外的搜索?

c++ - 让 QLabel 闪烁

java - 对数等for循环转换为求和表示法