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);
  }
}
6

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.

1

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.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest