When using an initializer list such as this:
for (int i : {3, 1, 6, 4})
{
std::cout << "i=" << i << std::endl;
}
The ouput is in the same order, 3, 1, 6, and finally 4. So I know the compiler must be using something similar to std::vector<int>
and not std::set<int>
.
Is this guaranteed? Where can I find the docs that explain how the compiler must interpret {3, 1, 6, 4}
.
You are creating an instance of std::initializer_list<int>
. See http://en.cppreference.com/w/cpp/utility/initializer_list for details.
From that page:
An object of type
std::initializer_list<T>
is a lightweight proxy object that provides access to an array of objects of typeconst T
.
The output order is guaranteed. However, that's not because the compiler creates a std::vector<int>
. It is guaranteed because there is an array of int
s underneath the initializer_list
.
Your range based loop is using the braced-init-list as a range expression which constructs a temporary object of type std::initializer_list<int>. The order is guaranteed because the 8.5.4.5. paragraph of the n4140 draft / standard states (emphasis mine):
An object of type std::initializer_list<E> is constructed from an initializer list as if the implementation allocated a temporary array of N elements of type const E, where N is the number of elements in the initializer list.
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