WK8FBnfhrQc5G9Mh
WK8FBnfhrQc5G9Mh

Reputation: 35

Initializing multidimensional vectors

How to initialize a vector of vectors?

The code below crashes my application.

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

Upvotes: 0

Views: 253

Answers (2)

juanchopanza
juanchopanza

Reputation: 227608

This will create a size 13 vector of size 4 vectors, with each element set to 50.

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

Upvotes: 2

DarkZeros
DarkZeros

Reputation: 8420

You need to resize it first:

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

Upvotes: 0

Related Questions