C++20 Improves For-Loop Syntax with Cleaner Index and Element Access
C++20 Improved the For-Loop Syntax
I discovered a small but powerful C++20 feature that lets range-based for-loops include an initializer, matching the clean syntax of Python and Lua. This change eliminates the need for manual index management, making code more readable and reducing boilerplate. I plan to use this quality-of-life improvement exclusively going forward.
It may seem very trivial, but small pieces of syntactic sugar like this pay large dividends when used across an entire codebase.
- UncleOxidant
Reading this, I really can't make much sense of it:
for (int i=0; auto&& it: vec)
cout << (++i) << ": " << it << endl;
It's certainly not obvious what's going on there at a glance.
This is at least a bit more pythonic:
for (auto [i, it] : std::views::enumerate(vec)) {
std::cout << i << ": " << it << "\n";
}
- HarHarVeryFunny
C++20 also has an enumerate() generator, so if you like the python syntax you can just do:
for (auto [i,v] : std::views::enumerate(vec))
std::cout << i << ": " << v << std::endl;
FWIW C++23 also has a python-like print and println:
std::println("{}: {}", i, v);
- adityamwagh
> 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.
This can’t be further from truth. C++ is essentially Frankenstein’s monster.
- WCSTombs
The C++20 version is still clearly inferior to the Python and Lua examples because you still have to manually increment the counter in the loop body. IMO the sibling comment by HarHarVeryFunny has a much better C++ equivalent for this idiom, even if it's slightly more verbose.
- WalterBright
C++ should copy D's elegance:
import std.stdio;
string[9] vec = [
"the", "quick", "brown", "fox",
"jumped", "over", "the", "lazy", "dog"
];
void main()
{
foreach (i, s; vec)
writeln(i, ": ", s);
}