Declaring a 2D vector(声明一个二维向量)
问题描述
在某些情况下,只有以下行有效.为什么会这样?
In some cases only the below line works.Why so?
vector< vector<int>> a(M,N);
这适用于任何情况.
vector< vector<int>> a(M, vector<int> (N));
有什么区别?
推荐答案
std::vector 有一个填充构造函数,它创建一个包含 n 个元素的向量并填充指定的值.a 具有 std::vector 类型,这意味着它是一个向量的向量.因此,填充向量的默认值是向量本身,而不是 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
这将创建一个 rows * cols 二维数组,其中每个元素都是 0.默认值是 std::vector 这意味着每一行都有一个向量,其中 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.
这篇关于声明一个二维向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声明一个二维向量
基础教程推荐
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- c++ STL设置差异 2022-01-01
