c++ - 使用基于范围的 for 循环时需要迭代器

标签 c++ c++11 for-loop iterator

目前,我只能使用以下方法进行基于范围的循环:

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,因为 valueit 总是同步的。

关于c++ - 使用基于范围的 for 循环时需要迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6953128/

相关文章:

c++ - 对于双映射

c++ - 在另一个线程正在运行的情况下退出应用程序时出错

python - 如何更改for循环的索引?

c++ - 具有管理员权限的 shellexecute 不会结束

c++ - 当函数获得 unique_ptr 的所有权抛出异常时对象销毁

C++ while 循环和 for 循环不起作用

r - 用于从 R 时间线手动采样的 for 循环的省时替代方案

c++ - 为什么 nullptr 在 C++11 中是小写的?

c++ - 移植的 C header 中的 NULL 与 nullptr

c++ - 如何在 C++ 的多重继承上下文中使用来自特定基类的运算符