Initializing a two dimensional std::vector

来源:互联网 发布:unity3d麻将开发思路 编辑:程序博客网 时间:2024/06/05 01:21

Definition:std::vector< std::vector <int> > fog;
Initialization:
not good one

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

recommend:
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

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

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 } };
0 0
原创粉丝点击