Need iterator when using ranged-based for loops(使用基于范围的 for 循环时需要迭代器)
问题描述
目前,我只能用这个做基于范围的循环:
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 循环时需要迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用基于范围的 for 循环时需要迭代器
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
