简体   繁体   中英

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

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()

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 .

You can use std::distance , or subtraction. std:distance has the advantage of working on iterators that don't provide random access (but uses specialization to provide the distance in constant time for random access iterators).

You can do this:

if(someFunction(*iter))  //got a hit on this string
{
   myIndex = std::distance(myStringVec.begin(), iter);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM