C++ 声明一个二维向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28663299/
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-28 21:01:58  来源:igfitidea点击:

Declaring a 2D vector

c++vectorstl

提问by sad

In some cases only the below line works.Why so?

在某些情况下,只有以下行有效。为什么会这样?

vector< vector<int>> a(M,N);

This works in every case.

这适用于所有情况。

vector< vector<int>> a(M, vector<int> (N));

What's the difference?

有什么不同?

回答by a_pradhan

std::vectorhas a fill constructor which creates a vector of n elements and fills with the value specified. ahas the type std::vector<std::vector<int>>which means that it is a vector of a vector. Hence your default value to fill the vector is a vector itself, not an int. Therefore the second options is the correct one.

std::vector有一个填充构造函数,它创建一个包含 n 个元素的向量并用指定的值填充。a具有类型std::vector<std::vector<int>>,这意味着它是向量的向量。因此,填充向量的默认值是向量本身,而不是int. 因此,第二种选择是正确的。

std::vector<std::vector<int>> array_2d(rows, std::vector<int>(cols, 0));

std::vector<std::vector<int>> array_2d(rows, std::vector<int>(cols, 0));

This creates a rows * cols 2D array where each element is 0. The default value is std::vector<int>(cols, 0)which means each row has a vector which has colsnumber of element, each being 0.

这将创建一个 rows * cols 2D 数组,其中每个元素都是 0。默认值是std::vector<int>(cols, 0)这意味着每行都有一个向量,该向量具有cols元素数量,每个元素都是 0。

回答by user10636234

For declaring a 2D vector we have to first define a 1D array of size equal to number of rows of the desired 2D vector. Let we want to create a vector of k rows and m columns

为了声明一个二维向量,我们必须首先定义一个大小等于所需二维向量行数的一维数组。让我们想创建一个 k 行 m 列的向量

 "vector<vector<int>> track(k);"

This will create a vector of size k. Then use resize method.

这将创建一个大小为 k 的向量。然后使用调整大小方法。

for (int i = 0; i < k; i++) {
    track[i].resize(m);

In this way you can declare a 2D vector

通过这种方式,您可以声明一个二维向量