声明2D向量 [英] Declaring a 2D vector

查看:58
本文介绍了声明2D向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,仅以下行有效。

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));

有什么区别?

推荐答案

std :: vector 具有fill构造函数,该构造函数创建n个元素的向量并填充指定的值。 a 具有类型 std :: vector< std :: vector< int>> 向量的向量。因此,用于填充向量的默认值是向量本身,而不是 int 。因此,第二个选项是正确的。

std::vector has a fill constructor which creates a vector of n elements and fills with the value specified. a has 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< std :: vector< int>> array_2d(rows,std :: vector< int>(cols,0));

这将创建一个行* cols二维数组,每个数组元素为0。默认值为 std :: vector< int>(cols,0),这意味着每一行的向量都具有 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 cols number of element, each being 0.

这篇关于声明2D向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆