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?

13th Jun 2017, 5:02 PM
Bryan
2 Antworten
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...
13th Jun 2017, 8:49 PM
Dennis
Dennis - avatar
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
13th Jun 2017, 9:14 PM
Bryan