初始化二维std :: vector [英] Initializing a two dimensional std::vector
本文介绍了初始化二维std :: vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,我有以下:
std::vector< std::vector <int> > fog;
我正在初始化它非常天真像:
and I am initializing it very naively like:
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);
}
它感觉很错了...还有另一种方法来初始化一个向量像这样?
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(
A_NUMBER,
std::vector<int>(OTHER_NUMBER)); // Defaults to zero initial value
如果值为其他零,例如 4
例如,必须为默认值:
If a value other zero, say 4
for example, was required to be the default then:
std::vector<std::vector<int>> fog(
A_NUMBER,
std::vector<int>(OTHER_NUMBER, 4));
仅仅提到在c ++ 11中引入的统一初始化,它允许初始化 vector
和其他容器,使用 {}
:
And just to mention uniform initialization 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文