初始化多维向量

时间:2013-11-12 21:59:23

标签: c++ vector multidimensional-array

如何初始化矢量矢量?

下面的代码会崩溃我的应用程序。

#include <iostream>
#include <vector>

int main()
{
    std::vector< std::vector< unsigned short > > table;
    for(unsigned short a = 0; a < 13; a++){
        for(unsigned short b = 0; b < 4; b++){
            table[a][b] = 50;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

这将创建一个大小为3的矢量大小为13的向量,每个元素设置为50。

using std::vector; // to make example shorter
vector<vector<unsigned short>> table(13, vector<unsigned short>(4, 50));

答案 1 :(得分:0)

您需要先调整大小:

std::vector<std::vector<unsigned short > > table;
table.resize(13);
for(unsigned short a = 0; a < 13; a++){
    table[a].resize(4);
    for(unsigned short b = 0; b < 4; b++){
        table[a][b] = 50;
    }
}
相关问题