矢量阵列中类的初始化

Initialization of classes within an STL array of vectors

本文关键字:初始化 阵列      更新时间:2023-10-16

我想知道是否可以在单个" 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似乎同意。