[英]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.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
.另请注意,为了便于移植(并可能消除编译器警告),
myIndex
的类型应为std::vector<std::string>::difference_type
而不是int
。
You can use std::distance
, or subtraction.您可以使用
std::distance
或减法。 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). std:distance
具有处理不提供随机访问的迭代器的优势(但使用专门化为随机访问迭代器提供恒定时间的距离)。
You can do this:你可以这样做:
if(someFunction(*iter)) //got a hit on this string
{
myIndex = std::distance(myStringVec.begin(), iter);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.