問題描述
目前,我只能用這個做基于范圍的循環:
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?
推薦答案
使用舊的 for
循環:
for (auto it = values.begin(); it != values.end(); ++it )
{
auto & value = *it;
//...
}
有了這個,你就有了 value
和迭代器 it
.想用什么就用什么.
With this, you've value
as well as iterator it
. Use whatever you want to use.
雖然我不推薦這樣做,但是如果您想使用基于范圍的 for
循環(是的,無論出于何種原因 :D),那么您可以這樣做這個:
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
}
這種方法避免了搜索給定的value
,因為value
和it
總是同步的.
This approach avoids searching given value
, since value
and it
are always in sync.
這篇關于使用基于范圍的 for 循環時需要迭代器的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!