Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most effective way to get the index of an iterator of an std::vector?

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?

like image 946
cairol Avatar asked Jan 28 '10 07:01

cairol


People also ask

What is the strongest iterator that list provides?

Random-Access Iterators: They are the most powerful iterators. They are not limited to moving sequentially, as their name suggests, they can randomly access any element inside the container.


1 Answers

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.

Note: it is a common name for a container iterator,std::container_type::iterator it;.

like image 145
UncleBens Avatar answered Oct 05 '22 05:10

UncleBens