【问题标题】:Initialization of classes within an STL array of vectors在 STL 向量数组中初始化类
【发布时间】:2012-10-30 21:37:24
【问题描述】:

我想知道是否可以在单个“行”内的向量数组中初始化一堆类。

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) }, { } };

您可以想象这个解决方案不起作用(否则我不会在这里!)。最快的方法是什么?

【问题讨论】:

    标签: c++ arrays vector c++11 initialization


    【解决方案1】:

    这样就行了,不需要重复提及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;
        }
      }
    }
    

    【讨论】:

    • 如果构造函数有多个参数怎么办?
    【解决方案2】:

    我认为应该允许这样做:

    #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 似乎同意。

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 2010-09-10
      • 2022-12-31
      • 1970-01-01
      • 2016-08-19
      • 1970-01-01
      • 2012-05-01
      • 2019-03-04
      • 2015-01-05
      相关资源
      最近更新 更多