假设我有一个 std::unordered_set<int>
命名为 myset
我想从 myset
返回一个随机数在O(1)
时间。我首先使用 rand()
生成一个随机数:
int n = rand() % myset.size();
然后,我做:
myset.begin() + n;
我想知道 myset.begin() + n
在O(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/