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.
std::max({vec[i], vec[j], vec[k]})into the program. You can't use astd::initializer_listto get data from a user, but you can build one from data from the user after you have it. Make sense?std::initiliazer_listis not. Once you create one, its size and the value of the elements inside it are constant. This is why you can't use it to get input. You can only create one and pass it around to be read from.max_elementwhen the number of element changes. For example, if you don't know if you will have 3 or 4 values to put in the initializer list, then you cannot usemax. In your case, you seem to know that it will always be 3 elements, which works withmaxeven if the value of the 3 elements changes at runtime.