Shibli
Shibli

Reputation: 6129

Memory allocation for multi-dimensional std::vector (C++)

Lets we have

std::vector <std::vector <int>> myVec;
myVec.resize(100);
myVec[0].push_back(1);
myVec[0].push_back(2);

When I break the program with a breakpoint, I see that both size and capacity of each myVec[] is zero. Additionally, when I try to access myVec[0][0], it gives access violation error. How this could be?

P.S.: I am using VS 10

Upvotes: 0

Views: 1447

Answers (1)

LihO
LihO

Reputation: 42085

Your code snippet seems to be perfectly correct. If you have problems with access violation, your problem is somewhere else.

Here's an example:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    vector<vector<int>> myVec;
    myVec.resize(100); // inserts 100 empty vectors into myVec
    myVec[0].push_back(1);
    myVec[0].push_back(2);
    cout << myVec[0][0] << ' ' << myVec[0][1] << endl;
    myVec[99].push_back(3);
    cout << myVec[99][0] << endl;
    return 0;
}

output:

1 2
3

If someone is confused by using resize for filling empty vector, check this

Hope this helps ;)

Upvotes: 1

Related Questions