Why is the following code illegal?
for (int index=0; index<3; index++)
{
cout << {123, 456, 789}[index];
}
While this works fine:
for (int value : {123, 456, 789})
{
cout << value;
}
Code in IDEOne: http://ideone.com/tElw1w
While std::initializer_list does not provide an operator[], it does have overloads for begin() and end() which are what the range based for uses. You can in fact index into an initializer_list like this:
for (int index=0; index<3; index++)
{
cout << begin({123, 456, 789})[index];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With