




MAIN.CXX
We can use the methods provided by the Standard Template Library vector instead of indices.
The method size() returns the number of elements in the vector.
The method front() returns the item at the front of the vector.
While the method back() returns the item at the back of the vector.
#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.front()->setPosition(3.0,4.0,10.0);
myBallArray.front()->setRadius(20.0);
myBallArray.front()->setVelocity(0.2,0.0,1.0);
while (1)
{
//report the ball position and velocity of the last ball created
cout << "ballNumber: " << myBallArray.size()-1 << endl;
cout << "myBall has position X: " << myBallArray.back()->getXPosition();
cout << " Y: " << myBallArray.back()->getYPosition();
cout << " Z: " << myBallArray.back()->getZPosition() << endl;
cout << "myBall has velocity X: " << myBallArray.back()->getXVelocity();
cout << " Y: " << myBallArray.back()->getYVelocity();
cout << " Z: " << myBallArray.back()->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);
}
}
//generate a random number between 0 and 100
int randomNumber = random()%100;
//create a new ball 50 percent of the time
if (randomNumber < 50)
{
//create a new ball
myBallArray.push_back(new ball);
//initialize the ball position
myBallArray.back()->setPosition(3.0,4.0,10.0);
myBallArray.back()->setRadius(20.0);
myBallArray.back()->setVelocity(0.2,0.0,1.0);
}
}
};