# Vector Iteration Problems

• 04-05-2004
PunkyBunny300
Vector Iteration Problems
Hi. I've declared a vector and now I want to add 1 to every spot in it that comes up from a random number generator. So if the number 6 came up I would want to increment vector[6] by 1. I have code that looks like it should be working but gives an error everytime the program is run.

Code:

``` vector <unsigned> Dicegame::PlayGame (unsigned numPlays) {         for (unsigned i = 0; i < myPlaysPerGame; i++)         {                 unsigned j = TossNDice();                 myGameResult[j]++;         }         return myGameResult.size(); }```
• 04-05-2004
Delete double post. You probably are getting an access violation, i.e. j is larger than the vector size.
• 04-05-2004
jlou
You should probably give more information about the error, and maybe more code (like how you initialze your vector). Also, please copy and paste your code when you post (if possible) because typos make it hard to distinguish the actual problem you are having.

Just like with a regular C-style array, you cannot access an element in the vector with [] unless an element actually exists (that index is not out of the bounds of the array). Your code is only safe if you know that TossNDice will only give you values within a particular range (e.g. 1-12) AND your vector has a size of one more than the highest number in that range (e.g. size of 13 because the indexes start at 0).

If you don't know the range that TossNDice will return, or if the range is too big to use a vector efficiently, try using a map. Your code will work properly as is.
• 04-06-2004
hk_mp5kpdw
Without seeing more of your Dicegame class it is more difficult to guess what the types of your variables are but I can try...
Quote:

Originally Posted by PunkyBunny300
vector <unsigned> Dicegame::PlayGame (unsigned numPlays)
...
return myGameResult.size();

If we are to assume that myGameResult is the vector, then you are returning an integer value (size_t type) when you have declared the return type to be a vector. This would seem to be one error.

Quote:

Originally Posted by PunkyBunny300
vector <unsigned> Dicegame::PlayGame (unsigned numPlays)
...
for (unsigned i = 0; i < myPlaysPerGame; i++)

You are passing in a variable that doesn't seem to get used at all. I can only guess, but perhaps this loop should read "i < numPlays". Again, without more knowledge of the structure of the class or purpose behind what the code is trying to do it is difficult to say.