How in the World to use an object inside a vector

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.:

GET_CLASS player1;
GET_CLASS player2;
GET_CLASS player3;
GET_CLASS player4;


where GET_CLASS is my class and the players are the objects.
Can anyone speak on how to declare an object within a vector? Thanks
Last edited on
closed account (zb0S216C)
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().

Wazzak

Last edited on
Does this help?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//  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?
Last edited on
@AbstractionAnon
That is incorrect. Where are you deleting the instance created in line 12 and why are you using new in the first place?
Fair point. Edited the example.

Topic archived. No new replies allowed.