Initializing classes in an array of STL vectors

I wanted to know whether it is possible to initialize a bunch of classes in an array of vectors inside one "string".

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

As you can imagine, this solution does not work (otherwise I would not be here!). What is the fastest way to do this?

+1
c ++ arrays initialization vector c ++ 11
source share
2 answers

This does this without having to mention A again:

 array<std::vector<A>, 3> v{{ {1}, {2,3,4}, {} }}; 

if the constructor takes two arguments, you must write them in braces:

 array<std::vector<A2>, 3> v2{{ {{1,2}}, {{2,3},{4,5},{8,9}}, {} }}; 

I would prefer the following syntax, which also works if the constructor is explicit.

 std::array<std::vector<A2>, 3> v2{{ {A2{1,2}}, {A2{2,3},A2{4,5},A2{8,9}}, {} }}; 

Full example:

 #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
source share

I believe this should be allowed:

 #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>{} }; 

In quick testing, g ++ 4.7.1 seems to agree.

0
source share

All Articles