5

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);
  }
}
Jan SE
  • 337
  • 5
  • 13
  • 1
    is it your array is fixed always ? – kiran Biradar Sep 19 '18 at 08:57
  • In your simple case, if this is the case at all, there is no need for pushing, just initialize it: http://coliru.stacked-crooked.com/a/074dc1039efb7613 – user1810087 Sep 19 '18 at 09:01
  • @kiranBiradar yes – Jan SE Sep 19 '18 at 09:18
  • @user1810087 In this simple example you are right. But in my code the vector is a member of a class. And when I create an object I have to specify the size of the vector. That's why I use v.reserve() – Jan SE Sep 19 '18 at 09:19
  • @JanSE you should probably mention this in your question. As it is now, it is confusing why the better answer for your current example is not the accepted one. – user1810087 Sep 19 '18 at 10:18
  • Possible duplicate of [Add same value multiple times to std::vector (repeat)](https://stackoverflow.com/questions/30998444/add-same-value-multiple-times-to-stdvector-repeat) – user1810087 Sep 19 '18 at 10:26

2 Answers2

9

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.

Marek R
  • 32,568
  • 6
  • 55
  • 140
  • I consider uniform initialisation a pure failure, so in consequence recommend *always* using parentheses anyway - even in case of initialiser list (`std::vector v({1, 2, 3});`) for consistency... – Aconcagua Sep 19 '18 at 09:11
7

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.

lubgr
  • 37,368
  • 3
  • 66
  • 117
  • 3
    While Marek's answer might be preferable on construction, this one is perfect for adding *additional* elements at some later point of time! – Aconcagua Sep 19 '18 at 09:13