[英]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. 以下代码将std :: array推回到std :: vector N次。 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: 您可以使用
std::vector::insert
(重载集中的#3)成员函数:
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. 请注意,@ MarekR的答案更适合初始化向量,因为它绕过了
reserve
的调用,并且在初始化期间设置对象通常比后续的成员函数调用更好。 The above call to std::vector::insert
instead is suitable for adding additional elements later on. 上面对
std::vector::insert
调用适用于稍后添加其他元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.