这段C++11代码对我来说很有效:
#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;
}
它打印出了六个预期的值。
但是,如果我将vector<str>
更改为array<str,3>
,gcc会给出以下错误:“std::array的初始值设定项过多”。
如果我这样改变fields
的初始化:
array<str,3> fields {
str{1,2}, str{3,4}, str{5,6}
};
事情进展得很顺利。
那么,在使用std::array
时,为什么我需要使用str{1,2}
,而在使用std::vector
时只需要{1,2}
呢?