获取std :: vector的迭代器索引的最有效方法是什么? [英] What is the most effective way to get the index of an iterator of an std::vector?
问题描述
我正在遍历一个向量,需要迭代器当前指向的索引。 AFAIK这可以通过两种方式完成:
I'm iterating over a vector and need the index the iterator is currently pointing at. AFAIK this can be done in two ways:
-
it - vec.begin()
-
std :: distance(vec.begin(),it)
it - vec.begin()
std::distance(vec.begin(), it)
这些方法的优点和缺点是什么?
What are the pros and cons of these methods?
推荐答案
我更喜欢 it - vec.begin()
正是由于Naveen给出的相反原因:如果将向量更改为列表,将不会编译。如果你在每次迭代中都这样做,你很容易就会把O(n)算法变成O(n ^ 2)算法。
I would prefer it - vec.begin()
precisely for the opposite reason given by Naveen: so it wouldn't compile if you change the vector into a list. If you do this during every iteration, you could easily end up turning an O(n) algorithm into an O(n^2) algorithm.
另一种选择,如果你迭代期间不要在容器中跳转,将索引保持为第二个循环计数器。
Another option, if you don't jump around in the container during iteration, would be to keep the index as a second loop counter.
这篇关于获取std :: vector的迭代器索引的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!