矢量阵列中类的初始化
Initialization of classes within an STL array of vectors
我想知道是否可以在单个" line"中的一个向量中初始化一堆类。
class A {
public:
A(int k) {...}
};
[...]
#include <array>
#include <vector>
using namespace std;
array<vector<A>, 3> = { { A(5), A(6) }, { A(1), A(2), A(3) }, { } };
您可以想象,此解决方案不起作用(否则我不会在这里!)。最快的方法是什么?
这样做,无需重复提及 A
:
array<std::vector<A>, 3> v{{ {1}, {2,3,4}, {} }};
如果构造函数进行了两个参数,则您会在牙套中写下它们:
array<std::vector<A2>, 3> v2{{ {{1,2}}, {{2,3},{4,5},{8,9}}, {} }};
我可能更喜欢以下语法,如果构造函数明确,也可以使用。
std::array<std::vector<A2>, 3> v2{{ {A2{1,2}}, {A2{2,3},A2{4,5},A2{8,9}}, {} }};
完整示例:
#include <array>
#include <vector>
#include <iostream>
struct A2 {
A2(int k,int j) : mk(k),mj(j) {}
int mk;
int mj;
};
int main (){
std::array<std::vector<A2>, 3> v2{{ {{1,2}}, {{2,3},{4,5},{8,9}}, {} }};
int i=0;
for (auto &a : v2){
std::cout << "... " << i++ <<std::endl;
for (auto &b : a){
std::cout << b.mk << " " <<b.mj <<std::endl;
}
}
}
我相信应该允许这样做:
#include <array>
#include <vector>
using namespace std;
class A {
public:
A(int k) {}
};
array<vector<A>, 3> v = { vector<A>{5, 6}, vector<A>{1, 2, 3}, vector<A>{} };
在快速测试中,G 4.7.1似乎同意。
相关文章:
- 阵列必须使用大括号封闭的初始器进行初始化
- 3D阵列C 的动态初始化
- 您应该如何在OpenGL 4.5中初始化立方体地图阵列
- 即使在C 中越过初始化阵列的极限后,结果也是如此
- 工会结构阵列的初始化太多
- 在C 中构造函数中初始化C阵列的错误
- 防止C 中阵列元素的构建/初始化
- 从其初始化的功能中使用的特定大小的阵列
- 阵列初始化结构
- SFINAE 在 VS10 中初始化阵列
- 静态成员的静态阵列:初始化顺序惨败的可能性
- 字符阵列未正确初始化
- DP阵列初始化的原因
- 阵列初始化器中的多余元素
- C 98如何在标题中初始化静态结构阵列
- 初始化字符串矢量阵列时的错误
- C 在结构初始化过程中带有内部阵列的奇怪错误
- 如何使用struct构造函数在结构中初始化指针阵列
- 用null C 初始化结构阵列
- 麻烦在G 中初始化阵列