当使用基于范围的for循环时需要迭代器 [英] Need iterator when using ranged-based for loops
问题描述
目前,我只能使用以下方式执行基于范围的循环:
for(auto& value:values)
但是有时我需要一个迭代器的值,而不是一个引用(无论什么原因)。是否有任何方法而不必通过整个向量比较值?
使用旧的
循环为:
for(auto it = values.begin(); it!= values。 end(); ++ it)
{
auto& value = * it;
// ...
}
code> value 以及迭代器 it
。
$ b 虽然我不建议这样做,但如果你想使用基于范围的 for
循环(是的,因为任何原因:D)你可以这样做:
auto it = std :: begin(values); // std :: begin是C ++中的一个自由函数11
for(auto& value:values)
{
//使用值或它 - 任何你需要的!
// ...
it ++; //在结尾或确保你在每次迭代中这样做
}
避免搜索 value
,因为 value
和 it
同步。
Currently, I can only do ranged based loops with this:
for (auto& value : values)
But sometimes I need an iterator to the value, instead of a reference (For whatever reason). Is there any method without having to go through the whole vector comparing values?
Use the old for
loop as:
for (auto it = values.begin(); it != values.end(); ++it )
{
auto & value = *it;
//...
}
With this, you've value
as well as iterator it
. Use whatever you want to use.
EDIT:
Although I wouldn't recommended this, but if you want to use range-based for
loop (yeah, For whatever reason :D), then you can do this:
auto it = std::begin(values); //std::begin is a free function in C++11
for (auto& value : values)
{
//Use value or it - whatever you need!
//...
it++; //at the end OR make sure you do this in each iteration
}
This approach avoids searching given value
, since value
and it
are always in sync.
这篇关于当使用基于范围的for循环时需要迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!