Svalorzen
Svalorzen

Reputation: 5608

Initialization of classes within an STL array of vectors

I wanted to know if it is possible to initialize a bunch of classes within an array of vectors within a single "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) }, { } };

As you can imagine this solution doesn't work (otherwise I wouldn't be here!). What is the fastest way to do it?

Upvotes: 1

Views: 408

Answers (2)

Johan Lundberg
Johan Lundberg

Reputation: 27028

This does it, without any need for repeated mentioning of A:

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

if the constructor took two arguments you would write them within braces:

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

I would probably prefer the following syntax which also 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;
    }
  }
}

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490128

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 a quick test, g++ 4.7.1 seems to agree.

Upvotes: 0

Related Questions