




MAIN.CXX
We can use random number generation and the delete statment to create a more flexible simulation.
Once a ball has been deleted, we must remove it from the vector with the erase method.
When an item is removed from a vector, the remaining indices shift down by one and the size decreases.
In order to avoid problems with indexing, we can use an iterator to access the items in the vector.
An iterator is a pointer to an item in a vector that we can iterate through in a for loop.
#include <vector.h>
#include <iostream.h>
#include "ball.h"
int main (void)
{
sphere mySphere;
mySphere.setRadius(10.0);
cout << "mySphere has radius: " << mySphere.getRadius() << endl;
sphere myOtherSphere;
myOtherSphere.copy(mySphere);
myOtherSphere.setPosition(3.0,4.0,10.0);
cout << "myOtherSphere has radius: " << myOtherSphere.getRadius() << endl;
cout << "myOtherSphere has X position: " << myOtherSphere.getXPosition() << endl;
vector<ball*> myBallArray;
//create a new ball
myBallArray.push_back(new ball);
//initialize the ball position
myBallArray[0]->setPosition(3.0,4.0,10.0);
myBallArray[0]->setRadius(20.0);
myBallArray[0]->setVelocity(0.2,0.0,1.0);
int ballNumber = 0;
while (1)
{
//report the ball position and velocity of the last ball created
cout << "myBall has position X: " << myBallArray[ballNumber]->getXPosition();
cout << " Y: " << myBallArray[ballNumber]->getYPosition();
cout << " Z: " << myBallArray[ballNumber]->getZPosition() << endl;
cout << "myBall has velocity X: " << myBallArray[ballNumber]->getXVelocity();
cout << " Y: " << myBallArray[ballNumber]->getYVelocity();
cout << " Z: " << myBallArray[ballNumber]->getZVelocity() << endl;
vector<ball*>::iterator i;
for (i=myBallArray.begin(); i!=myBallArray.end(); i++)
{
//simulate the ball flight
(*i)->fall();
//delete the ball if resting
if ((*i)->getZPosition() <= 0.0)
{
//delete the ball from memory
delete (*i);
//delete the ball from the vector
myBallArray.erase(i);
//decrement the number of balls in flight
ballNumber--;
}
}
//generate a random number between 0 and 100
int randomNumber = random()%100;
//create a new ball 50 percent of the time
if (randomNumber < 50)
{
//increment the number of balls in flight
ballNumber++;
//create a new ball
myBallArray.push_back(new ball);
//initialize the ball position
myBallArray[ballNumber]->setPosition(3.0,4.0,10.0);
myBallArray[ballNumber]->setRadius(20.0);
myBallArray[ballNumber]->setVelocity(0.2,0.0,1.0);
}
}
};