Sunday, August 2, 2009

How do I modify this simple C++ program to use a vector instead of an array?

The textbook I am using very briefly explains vectors and I don't fully understand it. One of the problems in the book wants me to modify an exercise program completed earlier to use a vector instead of an array. Can you help? Here's the code using an array:





#include %26lt;iostream%26gt;


#include %26lt;ctime%26gt;


using namespace std;





int rollDice();





int main()


{





int a[11];





for(int i = 0; i %26lt;=12 ; i++)


a[i]=0;





srand(time(0));





for(int counter = 1; counter%26lt;=36000; counter++){


a[rollDice()]++;


}





for (int j = 2; j %26lt;= 12; j++)


cout %26lt;%26lt; "The number of " %26lt;%26lt; j %26lt;%26lt; "'s rolled: " %26lt;%26lt; a[j] %26lt;%26lt; endl;





cout %26lt;%26lt; endl;


system("PAUSE");


return 0;


}





int rollDice()


{


int die1 = 1 + rand() % 6;


int die2 = 1 + rand() % 6;





int sum = die1 + die2;


return (die1 + die2);


}





The above program rolls 2 dice and outputs the # of times each possible total is rolled (2-12).

How do I modify this simple C++ program to use a vector instead of an array?
#include %26lt;vector%26gt;





vector%26lt;int%26gt; myVector;





for(int i=0; i%26lt;12; i++)


myVector.insert(i);





for(int i=0; i%26lt;myVector.size(); i++)


cout %26lt;%26lt; myVector[i];








you can also use an iterator like this:





vector%26lt;int%26gt;::iterator myVectorIterator = myVector.begin();


while(myVectorIterator != myVector.end()){


cout %26lt;%26lt; *myVectorIterator;


myVectorIterator++;


}
Reply:How about a vector of vectors instead of using an array...
Reply:My advice: Read the book, learn about vectors, and do it yourself.





This is not me trying to prevent you from getting the answer you need, but rather, telling you the best way I know of (from experience) to learn something and REMEMBER it better.

clematis

No comments:

Post a Comment