I have a little problem using vector of vector.
I have a std::vector<AObject*> _word
in my class, I build my word :
AObject *object = new Letters();
_word.push_back(object);
Later I use :
for (size_t i = 0 ; i < _word.size() ; ++i)
_word[i]->draw();
^ THIS WORKS BUT I NEED ANOTHER IMPLEMENTATION
But I need to use it this way :
In my class : std::vector<std::vector<AObject*> > _words;
AObject *obj = new Letters();
_word.push_back(obj);
_words.push_back(_word);
But I get a memory corruption ..
So I cannot use my vector of vector this way :
for (size_t i = 0 ; i < _words.size() ; ++i)
_words[0][i]->draw();
Thank you !
EDIT
I tried this :
for (size_t i = 0; i < _words.size() ; ++i)
{
for (size_t j = 0 ; j < _word.size() ; ++j)
_words[i][j]->draw();
}
You have a vector nested inside of a vector. Note the term nested. That implies that you need a nested loop of some kind to access the inner-most vector.
Let's have a simple example:
So
vect
has 4 items in it, all of these items arestd::vector<AObject*>
where each one has 3 items.Now when we do this:
the return value is 4 since this is the number of items in the "outer" vector.
Now, if we write a loop as you have done:
You are accessing in the loop (if we unroll it):
The problem is that there is no
vect[0][3]
. The inner vector has only 3 items in it, not 4 items. You are accessing memory that's out of bounds.So your indices are not correct. What you wanted to do was this:
So the loop should have been this: