C++ 如何初始化结构上的向量向量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21663256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize a vector of vectors on a struct?
提问by anat0lius
If I have a NxN matrix
如果我有一个 NxN 矩阵
vector< vector<int> > A;
How should I initialize it?
我应该如何初始化它?
I've tried with no success:
我试过没有成功:
A = new vector(dimension);
neither:
两者都不:
A = new vector(dimension,vector<int>(dimension));
回答by Joseph Mansfield
You use new
to perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.
您用于new
执行动态分配。它返回一个指向动态分配对象的指针。
You have no reason to use new
, since A
is an automatic variable. You can simply initialise A
using its constructor:
您没有理由使用new
,因为它A
是一个自动变量。您可以简单地A
使用其构造函数进行初始化:
vector<vector<int> > A(dimension, vector<int>(dimension));
回答by Kerrek SB
Like this:
像这样:
#include <vector>
// ...
std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));
(Pre-C++11 you need to leave whitespace between the angled brackets.)
(在 C++11 之前,您需要在尖括号之间留出空格。)