Tyler Shellberg
Tyler Shellberg

Reputation: 1356

Does using an initializer list in a loop work? If not, how does it fail and why?

The answers to this question imply that using an initializer list in a loop or with "unknown data" wouldn't work. They don't say why, or how it would fail.

IE, doing this: (this is a nonsense operation, but shows that the contents of the list would change as the loop progresses)

std::vector<float> vec;
// Assume vec is filled with some useful data

for(int i = 0; i < 10; i++) 
{ 
  for(int j = 0; j < 10; j++) 
  {
    for(int k = 0; k < 10; k++) 
    {
      result = std::max({vec[i], vec[j], vec[k]});
      // do something with result...
    }
  }
}

I have code that uses initializer lists to get the max of 3 or more elements very frequently. It seems like things are working, but I am not sure if they are or not.

I'd like to understand if it works. If not, how it fails and why.

I've used a very heavy set of warnings, nothing has ever reported "warning: may be using initializer list incorrectly" or so-on.

Upvotes: 1

Views: 55

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473447

The answers to this question imply that using an initializer list in a loop or with "unknown data" wouldn't work.

This is a misinterpretation of what was said, due to an omitted word. The statement you're talking about was in response to this comment:

How would you make this work if the data is generated in a loop, or the number of data changes at runtime?

Emphasis added. So when the person says:

If the data changes at runtime, ...

The response simply omitted the "number" part, since it's a direct response to the previous comment.

Braced-init-lists can contain arbitrary numbers of items, but the number of items in the list must be defined at compile-time.

Upvotes: 2

Related Questions