0
Random_shuffle question
https://code.sololearn.com/c8s6QRKXxb1D/#cpp I am attempting to make a hangman game. I first created a vector with the words I want to pick from. I then am trying to randomly arrange the words and select one at random. I am following a book on this. What I want to know is why some times it works and sometime the word it give me is blank? Is either words.begin() or words.end() pointing to a component that is not part of the vector such as words.end() being actually spot 10(the 11th spot). I have noticed however; if I remove the size initialization of the vector it will work. Can someone explain why it works without me specifying a starting vector size yet with the size it does not?
2 ответов
0
You are using the vector's fill constructor.
std::vector<std::string> words(10);
Creates a vector with 10 default constructed string elements.
Now you push 10 more elements into it and you end up with a vector like this: "","", ......, "", "", "alligator", "hippopotamus", etc...
Now you have a 50% chance of picking an empty spot.
You probably don't want to use the fill constructor in this case ^^
Tip:
Instead of repeating push_back the entire time, you can use the initializer list constructor like so:
std::vector<std::string> words = {"alligator", "hippopotamus", "orangutan"}; etc...
0
Thanks. The book I'm reading made it seem as if the (10) just set the size of the vector and that the push filled in those 10 spots