Just wondering how i would go about this problem. As you see I'm filling up a vector with objects of a struct knight. But I'm not sure how to get each object in the vector and give it a random value.
So basically I'm not sure how you call the object in the vector for giving it a value.
#include <iostream>
#include <vector>
struct Knight{
int health;
int armour;
int damage;
};
int main()
{
Knight *player = new Knight;
std::vector<Knight> *myKnightsOne = new std::vector<Knight>;
std::vector<Knight>::iterator *myKnightsIterator = new std::vector<Knight>::iterator;
for(int i = 0; i < 20; i++)
{
myKnightsOne->push_back(*player);
}
for(*myKnightsIterator = myKnightsOne->begin(); *myKnightsIterator != myKnightsOne->end(); *myKnightsIterator++)
{
//myKnightsOne->begin()->armour;
//How can i fill up the values here using vectorObject->damage = rand() % 50; Etc
}
return 0;
}
Cheers mate, hey i wouldn't do it all like this if I didn't have to. I'm currently a student at Atari so they are big on memory management. I'm partially new to c++ as well but just following the guide lines lol
One other question, say one of the knights in the vectors health equaled zero, is it possible to remove the knights health that equals zero from the vector. Or can you only remove and add elements from the end and front etc
Q1: Yes, you can, although if you intend to remove elements from the vector that are not at the very end, then a vector might not be best the choice, because deletes anywhere other than the last element are very expensive. vector<> has an erase( iterator ) method that you can use.
Q2: Normally you use -> to dereference the iterator to get at the referenced item. Hence the -> above. But your myKnightsIterator variable is a pointer to an iterator, hence we have to dereference the pointer to get at the iterator first. So essentially you need two dereferences: the first to get to the iterator and the second to get at the item. This syntax isn't legal: myKnightsIterator->->armour; so we have to use *. So (*myKnightsIterator) dereferences the pointer to get to the iterator, and then -> dereferences the iterator to get to the item.
I'm not sure if the parens are needed. If it compiles without them, then you don't need them. I put them in because I know it will work that way (I have not tried to compile anything).
It's a bit strange to declare a pointer to an iterator, hence my original comment. Doing so leads to the above messy syntax, and it doesn't really save anything because sizeof(std::vector<>::iterator) is either very close to sizeof( std::vector<>::iterator*) or equal to it (iterators are lightweight).
Cheers for that mate, but this is just a very small test program as well so it won't be much bigger than a good 100 lines. But thanks a heap for your input it's helped a lot :)