Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn an iterator into a scalar index?

Tags:

c++

iterator

Is there a way to determine the position of an iterator inside it's container? The "position" I'm looking would take the form of an integer value, that describes how far from the beginning of the container the iterator is.

For example,vector.front() would be 0, and vector.back() would be vector.size() - 1

like image 355
Anne Quinn Avatar asked Nov 21 '25 16:11

Anne Quinn


1 Answers

std::distance:

size_t index = std::distance( vector.begin(), it );

What it does behind the scenes is just it - v.begin() (for random access iterators, such as vector's). Otherwise, it just increments first argument until it reaches the second (which isn't particularly efficient).

like image 82
jrok Avatar answered Nov 23 '25 06:11

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!