Reputation: 2827
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()
Upvotes: 2
Views: 161
Reputation: 62975
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
.
Upvotes: 10
Reputation: 490128
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).
Upvotes: 5
Reputation: 361422
You can do this:
if(someFunction(*iter)) //got a hit on this string
{
myIndex = std::distance(myStringVec.begin(), iter);
}
Upvotes: 4