HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppCritical

What are the benefits of std::distance over subtracting iterators?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
benefitsiteratorsarestdthedistanceoversubtractingwhat

Problem

I'm iterating over a vector and need the index the iterator is currently pointing at. What are the pros and cons of the following methods?

  • it - vec.begin()



  • std::distance(vec.begin(), it)

Solution

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;.

Context

Stack Overflow Q#2152986, score: 709

Revisions (0)

No revisions yet.