I am trying to create a way to shuffle a vector of strings with out using the <algorithm> library. I am still learning about vectors but I have been struggling with the compiler crashing.
Here is the code I am using. Essentially what I am trying to do as a way of simple shuffling is to generate a random number for the index to choose within the boundaries of the vector size. Add the index to the bottom of the vector and delete the index of the random number. So even if the same random number is generated a different string will be chosen. If I do this process manually ( I choose the random number ) it works perfect. What am I doing wrong?
I don't see what is not working with the code you posted.
Either way, it still has several flaws. What you want to use is the Knuth-Fisher-Yates shuffle algorithm:
1 2 3 4 5
for (int i = vector_of_strings.size() - 1; i > 0; i--)
{
int n = random_int_in_range( 0, i + 1 );
swap( vector_of_strings[i], vector_of_strings[n] );
}
If you don't want to get a random number the correct way (avoiding bias), then the simple modulo trick would do:
1 2 3 4 5
for (int i = vector_of_strings.size() - 1; i > 0; i--)
{
int n = rand() % (i + 1);
swap( vector_of_strings[i], vector_of_strings[n] );
}