目前,我只能使用以下方法进行基于范围的循环:
for (auto& value : values)
但有时我需要一个值的迭代器,而不是引用(无论出于何种原因)。有没有什么方法不用遍历整个 vector 比较值?
最佳答案
使用旧的 for
循环:
for (auto it = values.begin(); it != values.end(); ++it )
{
auto & value = *it;
//...
}
有了这个,你就有了 value
和迭代器 it
。使用你想使用的任何东西。
编辑:
虽然我不建议这样做,但如果你想使用基于范围的 for
循环(是的,无论出于何种原因 :D),那么你可以这样做这个:
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
总是同步的。
关于c++ - 使用基于范围的 for 循环时需要迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6953128/