Search code examples
c++vectorpush-back

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

Solution

  • 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.