Reputation: 35
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
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
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