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

2023-01-20C/C++开发问题
4

本文介绍了使用基于范围的 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,因为valueit 总是同步的.

This approach avoids searching given value, since value and it are always in sync.

这篇关于使用基于范围的 for 循环时需要迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6