简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM