Elegant way to push back std::array to std::vector N times

Viewed 2675

the following codes pushed back an std::array to a std::vector N times. Is there a more elegant and shorter way of doing this?

#include <iostream>
#include <vector>
#include <array>

#include <iomanip>
#include <complex>
#include <cmath>

int main () {
  int N=10;
  std::vector< std::array<std::complex<double>,3> > v;
  v.reserve(N);
  for(int i=0;i<N;i++){
    std::array<std::complex<double>,3> el { {0.0,3.0,0.0} };
    v.push_back(el);
  }
}
2 Answers

Yes but you have to use parentheses when constructing vector

std::vector< std::array<std::complex<double>,3> > v(n, {0.0,3.0,0.0});

If braces are used than initialization list is preferred and in this case you could have unexpected errors.

You can use the std::vector::insert (#3 in the overload set) member function:

int N=10;
std::vector< std::array<std::complex<double>,3> > v;
v.reserve(N);

v.insert(v.end(), N,  { {0.0,3.0,0.0} });

Note that @MarekR's answer is preferable for initializing the vector, as it circumvents the call to reserve, and setting up an object during initialization is usually better than subsequent member function calls. The above call to std::vector::insert instead is suitable for adding additional elements later on.

Related