Initializing a two dimensional std::vector(初始化二维 std::vector)
问题描述
所以,我有以下几点:
std::vector< std::vector <int> > fog;
我很天真地初始化它:
for(int i=0; i<A_NUMBER; i++)
{
std::vector <int> fogRow;
for(int j=0; j<OTHER_NUMBER; j++)
{
fogRow.push_back( 0 );
}
fog.push_back(fogRow);
}
而且感觉很不对……有没有其他的方法可以像这样初始化一个vector?
And it feels very wrong... Is there another way of initializing a vector like this?
推荐答案
使用 std::vector::vector(count, value)
接受初始大小和默认值的构造函数:
Use the std::vector::vector(count, value)
constructor that accepts an initial size and a default value:
std::vector<std::vector<int> > fog(
ROW_COUNT,
std::vector<int>(COLUMN_COUNT)); // Defaults to zero initial value
如果一个非零值,例如 4
,需要作为默认值:
If a value other than zero, say 4
for example, was required to be the default then:
std::vector<std::vector<int> > fog(
ROW_COUNT,
std::vector<int>(COLUMN_COUNT, 4));
我还应该提到在 C++11 中引入了统一初始化,它允许使用 {}
初始化 vector
和其他容器:
I should also mention uniform initialization was introduced in C++11, which permits the initialization of vector
, and other containers, using {}
:
std::vector<std::vector<int> > fog { { 1, 1, 1 },
{ 2, 2, 2 } };
这篇关于初始化二维 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:初始化二维 std::vector


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01