Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::vector and std::array initializer lists

Tags:

This C++11 code works fine for me:

#include <iostream>
#include <vector>
#include <array>
using namespace std;

struct str {
    int first, last;
};


vector<str> fields {
    {1,2}, {3,4}, {5,6}
};

int main()
{
    for (str s : fields)
        cout << s.first << " " << s.last << endl;
}

It prints the six expected values.

But if I change vector<str> to array<str,3>, gcc gives me this error: "too many initializers for ‘std::array’".

If I change the initialization of fields thus:

array<str,3> fields {
    str{1,2}, str{3,4}, str{5,6}
};

Things work nicely.

So why do I need str{1,2} when using std::array, but only {1,2} when using std::vector?