Vector of Vector of object

144 views Asked by At

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();
}
2

There are 2 answers

0
PaulMcKenzie On BEST ANSWER

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:

std::vector<std::vector<AObject*>> vect;
//...
std::vector<AObject*> inner = {new AObject, new AObject, new AObject};
//...
vect.push_back(inner);
vect.push_back(inner);
vect.push_back(inner);
vect.push_back(inner);

So vect has 4 items in it, all of these items are std::vector<AObject*> where each one has 3 items.

Now when we do this:

vect.size()

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:

for (size_t i = 0 ; i < vect.size() ; ++i)  
    vect[0][i]->draw();

You are accessing in the loop (if we unroll it):

vect[0][0]->draw();  // good
vect[0][1]->draw();  // good
vect[0][2]->draw();  // good
vect[0][3]->draw();  // <-- error

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:

vect[0][0]->draw();  // good
vect[0][1]->draw();  // good
vect[0][2]->draw();  // good

vect[1][0]->draw();  // good
vect[1][1]->draw();  // good
vect[1][2]->draw();  // good

vect[2][0]->draw();  // good
vect[2][1]->draw();  // good
vect[2][2]->draw();  // good

vect[3][0]->draw();  // good
vect[3][1]->draw();  // good
vect[3][2]->draw();  // good

So the loop should have been this:

for (size_t i = 0 ; i < vect.size() ; ++i)  
{
   size_t innerSize = vect[i].size(); 
   for (size_t j = 0; j < innerSize; ++j )
      vect[i][j]->draw();
}
0
R Sahu On

You are using the indices incorrectly in the block below:

for (size_t i = 0 ; i < _words.size() ; ++i)  
      _words[0][i]->draw();

it should be:

for (size_t i = 0 ; i < _words.size() ; ++i)  
      _words[i][0]->draw();
//           ^^^^ reverse i and 0