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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:45:48  来源:igfitidea点击:

How to initialize a vector of vectors on a struct?

c++vector

提问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 newto perform dynamic allocation. It returns a pointer that points to the dynamically allocated object.

您用于new执行动态分配。它返回一个指向动态分配对象的指针。

You have no reason to use new, since Ais an automatic variable. You can simply initialise Ausing 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 之前,您需要在尖括号之间留出空格。)