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
If I had to use Python, I’d write something like this:
1 vec = [ 2 " the " , " quick " , " brown " , " fox " , 3 " jumped " , " over " , " the " , " lazy " , " dog " 4 ] 5 6 7 8 for i , it in enumerate ( vec , start = 1 ) : 9 print ( f " { i } : { it } " )
And if I were to use Lua, it might look like this:
1 local vec = { 2 " the " , " quick " , " brown " , " fox " , 3 " jumped " , " over " , " the " , " lazy " , " dog " 4 } 5 6 7 8 for i , it in ipairs ( vec ) do 9 print ( i .. " : " .. it ) 10 end
But if I were to use C++17 or older, the equivalent approach would look like this:
1 vector < string > vec = { 2 " the " , " quick " , " brown " , " fox " , 3 " jumped " , " over " , " the " , " lazy " , " dog " 4 } ; 5 6 7 8 for ( int i = 0 ; i < vec . size ( ) ; ++ i ) 9 { 10 auto && it = vec [ i ] ; 11 cout << i << " : " << it << endl ; 12 }
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 it’s loop scope with an additional statement.
... continue reading