12

I can achieve identical output by using different containers in C++. For example . .

    std::array<int, 5> v = {1,2,3,4,5};
    for(auto i : v)
        std::cout << i << ", ";

or

    std::vector<int> v = {1,2,3,4,5};

or

    int v[] = {1,2,3,4,5};

etc . .

So what container does auto use here?

    auto v = {1,2,3,4,5};
    for(auto i : v)
        std::cout << i << ", ";

1 Answer 1

19

std::initializer_list<int>


Not that hard to check for yourself, you can always decltype(v), and then compare it with said list type.

That has another nice property, that sometimes is very useful and might interest you:

for (auto i : {1,2,3,4,5})
    std::cout << i << ", ";

It can be done because initializer_list keeps the standard range interface.

2
  • 1
    <tomalak> << TYPE_DESC(v); auto v = {1,2,3,4,5}; / <geordi> lvalue initializer_list<int> Correct. +1 Jun 28, 2013 at 9:44
  • 3
    Two little remarks: Strictly speaking, initializer_list is not a container in the sense of the standard. Your example works, because the standard explicitely defines ranged-based for statements of that form. At first sight there is no entity of type initializer_list. Such an object is introduced implicitely, so you have to include <initializer_list>, but you cannot "see" it.
    – MWid
    Jun 29, 2013 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.