0

I'm currently initializing a vector like this:

struct Foo{
  Foo(double a, double b){
    a_ = a;
    b_ = b;
  };
  double a_;
  double b_;
};

std::vector<Foo> foo_vec{{1, 2}, {2, 3}};

This correctly constructs a vector with two initialized elements. I'd like to pull this initialization out to a const global variable because I'm using the same one multiple times for different vectors. I tried this:

// this fails to compile: result type must be constructible from value type of input range
const std::array<std::initializer_list<double>, 2> bar = {{{1, 2}, {2, 3}}};
std::vector<Foo> foo_vec{bar.begin(), bar.end()};

// this works
const std::array<Foo, 2> bar = {{{1, 2}, {2, 3}}};
std::vector<Foo> foo_vec{bar.begin(), bar.end()};

Are there any other shorter/better ways to do this or is this it?

vitalstatistix
  • 310
  • 2
  • 8
  • The first doesn't work because `Foo` does not define a constructor that accepts `std::initializer_list` (while default constructor is deleted) – Sergey Kolesnik May 19 '22 at 09:31
  • Does this answer your question? [std::initializer\_list constructor](https://stackoverflow.com/questions/48496848/stdinitializer-list-constructor) – Sergey Kolesnik May 19 '22 at 09:35

1 Answers1

2

Why do you want to mess with initializer lists? Just copy a vector:

const std::vector<Foo> default_vec{{1, 2}, {2, 3}};
std::vector<Foo> foo_vec{default_vec};
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42