0

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

BЈовић
  • 62,405
  • 41
  • 173
  • 273
Shibli
  • 5,879
  • 13
  • 62
  • 126
  • should you also `myVec[0].resize`? – Dan Jan 29 '12 at 20:49
  • Besides this being invalid syntax, where do you breakpoint it, and where do you access `myVec[0][0]`? If you access it after the first `push_back` then it should be fine. @Dan he doesn't need to since he's doing `push_back` – Seth Carnegie Jan 29 '12 at 20:50
  • 1
    @Dan: But I already use `push_back()` which allocates memory. – Shibli Jan 29 '12 at 20:50
  • 1
    @Shibli Please post your actual code. This can't be it because `` won't compile. – Seth Carnegie Jan 29 '12 at 20:53
  • 3
    I just added < > around int to make it compile and this works fine in my VS2010. Btw, just so we are on the same page, this isn't multi-dimensional vector. This is a vector of vectors, not exactly the same thing. If you want true multi dimensional array-based storage, you would have to use one of Boost libraries – DXM Jan 29 '12 at 20:56
  • @DXM: Won't vector of vectors does the same thing considering I don't need somehing sophisticated? – Shibli Jan 29 '12 at 21:05
  • 1
    At which point you have tried to access myVec[0][0], before or after the `push_back`? – Christian Ammer Jan 29 '12 at 21:17
  • @Shibli: Just making sure you understand the difference, but yeah, you are free to use whatever makes sense for you. Multidimensional arrays are sometimes nicer because they use one continuous block of memory where as N by M vector of vectors will allocate M + 1 blocks of memory, but now we are talking optimization which shouldn't be a concern for 99% of cases. For more on the difference, see http://stackoverflow.com/questions/597720/what-is-differences-between-multidimensional-array-and-array-of-arrays-in-c – DXM Jan 29 '12 at 22:25

1 Answers1

1

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

LihO
  • 41,190
  • 11
  • 99
  • 167