阅读一些基于范围的循环示例,他们提出了两种主要方法 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 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)