How C++20 improved the for-loop syntax
How C++20 improved the for-loop syntax
C++20 如何改进了 for 循环语法
Here’s a small piece of syntactic sugar from C++20. Let’s say I wanted to print out the following: 1: the 2: quick 3: brown 4: fox 5: jumped 6: over 7: the 8: lazy 9: dog 这是 C++20 中一个小小的语法糖。假设我想打印出以下内容:1: the 2: quick 3: brown 4: fox 5: jumped 6: over 7: the 8: lazy 9: dog
If I had to use Python, I’d write something like this: 如果我使用 Python,我会这样写:
vec = [
"the", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
]
for i, it in enumerate(vec, start=1):
print(f"{i}: {it}")
And if I were to use Lua, it might look like this: 如果我使用 Lua,它看起来可能是这样的:
local vec = {
"the", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
}
for i, it in ipairs(vec) do
print(i .. ": " .. it)
end
But if I were to use C++17 or older, the equivalent approach would look like this: 但如果我使用 C++17 或更早的版本,等效的写法如下:
vector<string> vec = {
"the", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
};
for (int i = 0; i < vec.size(); ++i)
{
auto&& it = vec[i];
cout << i << ": " << it << endl;
}
The common theme of these examples is that they produce a for-loop that includes in its scope both an index value and element reference. C++ stands out for having to introduce the reference to its loop scope with an additional statement. 这些示例的共同点在于,它们生成的 for 循环在其作用域内同时包含了索引值和元素引用。C++ 的不同之处在于,它必须通过额外的语句将引用引入循环作用域。
With C++20, it is now possible to create an example that matches the other languages, and it looks like this: 有了 C++20,现在可以写出与上述其他语言相匹配的代码了,如下所示:
vector<string> vec = {
"the", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
};
for (int i=0; auto&& it: vec)
cout << (++i) << ": " << it << endl;
The specific proposal that enables this is called “Range-based for statements with initializer,” and it is very similar to a previous proposal from C++17, “If statement with initializer.” What I have demonstrated in this post is precisely the intended use-case for this language feature. 实现这一功能的具体提案被称为“带有初始化器的基于范围的 for 语句”(Range-based for statements with initializer),它与 C++17 中的“带有初始化器的 if 语句”非常相似。我在本文中演示的正是该语言特性的预期用例。
I really like it. It may seem very trivial, but small pieces of syntactic sugar like this pay large dividends when used across an entire codebase. I’ve only just discovered it myself, but I intend to use it exclusively over the traditional approach going forward. 我非常喜欢它。这看起来可能微不足道,但当在整个代码库中使用时,这类小小的语法糖会带来巨大的收益。我也是刚刚才发现它,但我打算在今后的开发中完全用它来替代传统写法。
It seems to me that the C++ Standards Committee is doing a decent job maintaining the language, and introducing useful features when it makes sense to do so. Have you discovered any small quality-of-life features such as this? If so, let me know! Send a message to mail@lzon.ca, or DM me on one of my social accounts on the homepage. 在我看来,C++ 标准委员会在维护语言方面做得不错,并且在合理的情况下引入了有用的特性。你是否也发现过类似这样的小型“生活质量”(quality-of-life)特性?如果有,请告诉我!发送邮件至 mail@lzon.ca,或通过主页上的社交账号私信我。