Ok, so I'm trying to randomly assign names out of a vector storing these names. But, I believe my vector is larger than the number of actual elements I have because about 10% of the time I end up getting a blank string for a name. How do I deal with this?
Common, you should be able to do better than that. http://www.cplusplus.com/forum/articles/40071/#msg216313
If you didn't popullated the 10% of the vector with empty strings, I would say that you are accessing out of bounds.
Ah sorry I shoulda known better than that :/ I was posting from my phone. But yea, my vector is populated from a file, and I don't populate the rest. I figured if I was accessing out of bounds, I would either get a crash or it'd print garbage.
if(names.empty() != true)
{
srand(time(NULL));
int i = rand() % names.size() + 1;
name = names[i];
}
else
std::cout << "Error: Name vector not populated.";
And rand() % (x+1) gives you numbers from 0 to x. x is out of bounds.
rand() % x + 1 gives you numbers from 1 to x. Division takes precedence over addition.
Oh wow, that fixed it. For some reason I thought size was giving me 1 less than the number I was wanting. I must confess I don't understand the usage of modulus all the time