Jan*_* SE 3 c++ vector push-back
以下代码将std :: array推回到std :: vector N次.这样做有更优雅,更短的方式吗?
#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);
}
}
Run Code Online (Sandbox Code Playgroud)
是的但你必须在构造矢量时使用括号
std::vector< std::array<std::complex<double>,3> > v(n, {0.0,3.0,0.0});
Run Code Online (Sandbox Code Playgroud)
如果使用大括号,则首选列表是首选,在这种情况下,您可能会遇到意外错误.
您可以使用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} });
Run Code Online (Sandbox Code Playgroud)
请注意,@ MarekR的答案更适合初始化向量,因为它绕过了调用reserve,并且在初始化期间设置对象通常比后续的成员函数调用更好.以上调用std::vector::insert适用于稍后添加其他元素.