Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
  }
}
like image 613
Jan SE Avatar asked Dec 03 '22 19:12

Jan SE


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.

like image 136
Marek R Avatar answered Dec 28 '22 22:12

Marek R


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.

like image 20
lubgr Avatar answered Dec 28 '22 22:12

lubgr