有效的方法来获取迭代器的索引? [英] Effective way to get the index of an iterator?
本文介绍了有效的方法来获取迭代器的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我迭代一个向量,需要迭代器当前指向的索引。 AFAIK这可以通过两种方式完成:
-
it - vec.begin()
-
std :: distance(vec.begin
正是由于Naveen给出的相反的原因:所以如果你将向量转换为列表,它不会编译。如果你在每次迭代中这样做,你可以很容易地将一个O(n)算法转换成一个O(n ^ 2)算法。
这些方法的利弊是什么?
解决方案code> it - vec.begin()
在迭代过程中不要在容器中跳转,将索引保存为第二个循环计数器。
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)
What are the pros and cons of these methods?
解决方案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.
这篇关于有效的方法来获取迭代器的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文