除了递增语句,如何使for循环变量const? [英] How to make a for loop variable const with the exception of the increment statement?
问题描述
考虑循环标准:
for (int i = 0; i < 10; ++i)
{
// do something with i
}
我想防止在for
循环的主体中修改变量i
.
I want to prevent the variable i
from being modified in the body of the for
loop.
但是,我不能将i
声明为const
,因为这会使增量语句无效.有没有办法在增量语句之外使i
成为const
变量?
However, I cannot declare i
as const
as this makes the increment statement invalid. Is there a way to make i
a const
variable outside of the increment statement?
推荐答案
从c ++ 20开始,您可以使用 ranges :: views :: iota 像这样:
From c++20, you can use ranges::views::iota like this:
for (int const i : std::views::iota(0, 10))
{
std::cout << i << " "; // ok
i = 42; // error
}
这是演示.
从c ++ 11开始,您还可以使用以下技术,该技术使用IIILE(立即调用的内联lambda表达式):
From c++11, you can also use the following technique, which uses an IIILE (immediately invoked inline lambda expression):
int x = 0;
for (int i = 0; i < 10; ++i) [&,i] {
std::cout << i << " "; // ok, i is readable
i = 42; // error, i is captured by non-mutable copy
x++; // ok, x is captured by mutable reference
}(); // IIILE
这是演示.
请注意,[&,i]
表示i
是由非可变副本捕获的,其他所有内容都是由可变引用捕获的.循环末尾的();
只是意味着立即调用lambda.
Note that [&,i]
means that i
is captured by non-mutable copy, and everything else is captured by mutable reference. The ();
at the end of the loop simply means that the lambda is invoked immediately.
这篇关于除了递增语句,如何使for循环变量const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!