Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the index when using a vector<>::iterator

Tags:

c++

I wonder if there is a way to get the index of random access iterator. For example:

int myIndex = -1;
for(std::vector<std::string>::iterator iter = myStringVec.begin();
    iter != myStringVec.end();
    iter++)
{
  if(someFunction(*iter))  //got a hit on this string
    myIndex = ...
}

Beg you pardon if this is super trival. An obvious solution would be to iterate by index, but my thinking is that was thinking for random access iterators, there might be a way for the iterator to tell you what it's index is, like myIndex = iter.index()

like image 848
2NinerRomeo Avatar asked Aug 30 '26 21:08

2NinerRomeo


1 Answers

myIndex = iter - myStringVec.begin();

or

myIndex = std::distance(myStringVec.begin(), iter);

Also note that to be portable (and possibly to eliminate compiler warnings), myIndex should be of type std::vector<std::string>::difference_type rather than int.

like image 97
ildjarn Avatar answered Sep 02 '26 11:09

ildjarn