Accessing class functions in a vector

Hello guys!

I'd like to know how I can use class functions in a vector.

I have 2 classes:
Gamemode class
bullets class

Inside the Gamemode class I declared:
vector<bullets> Bullet and bullets * b.

If the user presses the shoot button a new bullets class will be added to the Bullet vector:
b = new bullets;
Bullet.push_back(b)

now I'd like to check all objects in the Bullet vector for the collision() function inside the bullets class.

I already set up a for loop which counts from 0 to the end of the vector:
for( int i=0;i<Bullet.size;i++)
{
}


My idea was to do something like:
if(Bullet[i].collision()) then erase Bullet[i]

But that doesn't work...

Do you know how I could solve this?
I'm googleling for hours now and can't find
any solution.

Thanks for your help!
--------------
er4zox

You are using the wrong kind of vector instantiation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
vector<bullets*> bullet_collection; //Note that this is a collection of pointers
bullets* b;
//...Press shoot...
b = new bullets();
bullet_collection.push_back(b); //now you are pushing back the correct type
while(bullet_collection.size() > 0){
   if(bullet_collection.back()->collision()) blah();
      //Because it is a container of pointers, use '->' instead of '.'
   delete bullet_collection.back();
   bullet_collection.pop_back();
}

//Or, if you don't want a container of pointers (probably for the best)
vector <bullets> bullet_collection;
bullets* b;
//...Press shoot...
b = new bullets();
bullet_collection.push_back(*b); //Note the dereference to get the actual object
delete b;
//etc. 


You might also want to consider not using pointers at all for this part of your program.
Without testing


1
2
3
4
5
6
7
8
9
10
11
12
13
14
for ( auto &b : Bullet )
{
   if ( b->collision() )
   {
      delete b;
      b = nullptr;
   }
}

Bullet.erase( 
   std::remove_if( Bullet.begin(), 
                   Bullet.end(), 
                   std::bind2nd( std::equal<bullets *>(), nullptr ) ), 
   Bullet.end() );
Last edited on
Topic archived. No new replies allowed.