Quick Q: What type does auto use for containers? -- StackOverflow

Quick A: std::initalizer_list. And did you know you can even do for(auto i: {1,2,3,4,5}) ?

What type does auto use for containers?

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 << ", ";

Add a Comment

Comments are closed.

Comments (6)

0 0

Gennaro Prota said on Jun 28, 2013 06:43 PM:

Except that std::initializer_list's are not containers.

BTW, things like the for example in the "Quick A" show IMO that initializer_list should have been renamed to something more general, like e.g. "tuple_literal" or similar.
0 0

Greg Marr said on Jun 29, 2013 09:11 PM:

Since it only has a single type, anything with tuple would have been misleading.
0 0

Gennaro Prota said on Jun 30, 2013 05:00 AM:

@Greg Marr:

care to explain? (That name was just off the top of my head, anyway.)
0 0

Greg Marr said on Jun 30, 2013 07:31 AM:

All values in an initializer_list are the same type, as it is template<typename T> class initializer_list;

The values in a tuple can all be different types, as it is template<typename... Ts> class tuple;
0 0

Gennaro Prota said on Jun 30, 2013 01:25 PM:

I suspected you meant this but wasn't sure. Yes, one should have come up with something else... perhaps "sequence_literal".
0 0

Greg Marr said on Jun 30, 2013 08:45 PM:

They're initializers, and there can be more than one of them, so it's a list. I'm fine with the name.