基于范围的循环:按值获取项目还是对 const 的引用?

2023-02-12C/C++开发问题
3

本文介绍了基于范围的循环:按值获取项目还是对 const 的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

阅读一些基于范围的循环示例,他们提出了两种主要方法 1,2、3, 4

Reading some examples of range based loops they suggest two main ways 1, 2, 3, 4

std::vector<MyClass> vec;

for (auto &x : vec)
{
  // x is a reference to an item of vec
  // We can change vec's items by changing x 
}

for (auto x : vec)
{
  // Value of x is copied from an item of vec
  // We can not change vec's items by changing x
}

嗯.

当我们不需要更改 vec 项时,IMO、Examples 建议使用第二个版本(按值).为什么他们不建议 const 引用的东西(至少我没有找到任何直接的建议):

When we don't need changing vec items, IMO, Examples suggest to use second version (by value). Why they don't suggest something which const references (At least I have not found any direct suggestion):

for (auto const &x : vec) // <-- see const keyword
{
  // x is a reference to an const item of vec
  // We can not change vec's items by changing x 
}

不是更好吗?当它是一个const 时,它不是避免了每次迭代中的冗余副本吗?

Isn't it better? Doesn't it avoid a redundant copy in each iteration while it's a const?

推荐答案

如果你不想改变项目又想避免复制,那么 auto const & 是正确的选择:

If you don't want to change the items as well as want to avoid making copies, then auto const & is the correct choice:

for (auto const &x : vec)

建议您使用 auto & 的人是错误的.忽略它们.

Whoever suggests you to use auto & is wrong. Ignore them.

这里是回顾:

  • 如果要处理副本,请选择 auto x.
  • 如果您想使用原始项目并可能对其进行修改,请选择 auto &x.
  • 如果您想使用原始项目而不修改它们,请选择 auto const &x.

这篇关于基于范围的循环:按值获取项目还是对 const 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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