Help with Vectors

Started by
4 comments, last by Driv3MeFar 17 years, 9 months ago
Heya all, I have another noob problem, this time concerning vectors. I've just started using them to build dynamic sprite sheets, and they've worked perfectly so far. I thought they worked so well, I started applying them in other ways. This one has me stumped: I have "monsters" declared as: std::vector<npcClass> monsters; the code giving me problems is: npcClass temp; temp.SetImage(monsterImages[g_currentMonster]); temp.setX(g_mouseX); temp.setY(g_mouseY); fprintf(stdout, "Writing Monster: X: %d Y: %d\ #:%d\n", temp.getX(), temp.getY(), monsters.size()); monsters.push_back(temp); fprintf(stdout, "Writing Monster: X: %d Y: %d\ #:%d\n", monsters.begin()->getX(), monsters.begin()->getY(), monsters.size()); Here is the stdout info produced: Writing Monster: X: 274 Y: 158 #:0 Writing Monster: X: -842150451 Y: -842150451 #:1 Writing Monster: X: 290 Y: 215 #:1 Writing Monster: X: -842150451 Y: -842150451 #:2 Writing Monster: X: 523 Y: 358 #:2 Writing Monster: X: -842150451 Y: -842150451 #:3 Writing Monster: X: 600 Y: 218 #:3 Writing Monster: X: -842150451 Y: -842150451 #:4 It's obvioius that temp isn't being passed correctly, but i'm not sure why. As always, thanks in advance for the help :)
~Argonaut________________________________Why "~Argonaut"? It's all just a mathematical expression denoting a close approximation of "Argonaut", which is irrational and can't be precisely defined.
Advertisement
Store pointers to your npcClass in the vector, and allocate them on the heap (ie, with new).

Edit: Which would look like this:

std::vector< npcClass* > monsters;

npcClass *temp = new npcClass();
temp->SetImage(...);
...
monsters.push_back(temp);
Yep, worked like a charm! Thanks for the help :)
~Argonaut________________________________Why "~Argonaut"? It's all just a mathematical expression denoting a close approximation of "Argonaut", which is irrational and can't be precisely defined.
No problem, just dont forget that now all elements of your vector will need to be deleted at some point.
Ahh, I didn't think of that. The npcClass handles its destruction correctly, is there something more that I need to do with vectors?
~Argonaut________________________________Why "~Argonaut"? It's all just a mathematical expression denoting a close approximation of "Argonaut", which is irrational and can't be precisely defined.
Nothing specifically for the vectors themselves, but since every instance of npcClass you push into the vector gets new'd, they must, somewhere, be deleted.

Basically, once you're done with the vector, you'll need to do something like this:

std::vector< npcClass* >::iterator it = monsters.begin();
for ( it; it != monsters.end(); ++it() )
{
delete (*it);
}

[Edited by - Driv3MeFar on July 5, 2006 10:52:14 PM]

This topic is closed to new replies.

Advertisement