Ok so I have looked all through my book and have not seen anywhere how to use an object within a vector. I've been making a simple game using classes for the last couple of days and have found that it would be much easier/faster to just use a vector for my objects instead of declaring 4 independent objects. e.g.:
There's two ways to get an object from a std::vector:
• std::vector::at(). This obtains an object from a std::vector based on the index you give it.
• std::vector::operator[]. This also obtains an object from a std::vector based on the index you give it.
Here's some working examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
struct Object
{
Object(int V_ = 0) : X_(V_) { }
Object(Object const &O_) : X_(O_.X_) { }
int X_;
};
int main()
{
std::vector<Object> Objects_;
Objects_.push_back(10);
Objects_.push_back(20);
// Get the first object in the vector:
Objects_.at(0u).X_ = /*...*/;
// Get the second object in the vector:
Objects_[1u].X_ = /*...*/;
}
The difference between the two is std::vector::at() provides bounds-checking, while std::vector::operator[] does not.
Also, you don't declare objects inside a std::vector: you add them with std::vector::push_back(), and remove them with std::vector::pop_back().
// Declare the vector
vector<GET_CLASS> players;
// Create an iterator to traverse the vector
vector<GET_CLASS>::iterator iter;
bool end_of_game = false;
// Populate the vector
for (int i=0; i<4; i++)
{ // Create a player
GET_CLASS player;
// Set some player attributes here
// Add the player to the vector
players.push_back (player);
}
// Now play the game
while (! end_of_game)
{ // Iterate through the players
for (iter=players.begin(); iter!=players.end(); iter++)
iter->Do_Move ();
}
BTW, it seems a little weird to call your class GET_CLASS, wouldn't PLAYER make more sense?