Shuffling a vector of strings

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.
1
2
3
4
5
6
7
8
 for (unsigned int j = 0; j < vector_of_strings.size(); j++)
		{
			int random_number = rand() % (MAX_RAND_NUM - MIN_RAND_NUM + 1) + MIN_RAND_NUM;

			vector_of_strings.push_back(vector_of_strings[random_number]);
			vector_of_strings.erase(vector_of_strings.begin() + random_number);
		}
		


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] );
}

Please do it the right way.

For random_int_in_range(), see here:
http://www.cplusplus.com/faq/beginners/random-numbers/#random_int_in_range

For more on the problem with your extant algorithm, see:
http://blog.codinghorror.com/the-danger-of-naivete/


The other option is to just use the std::shuffle() algorithm.

Hope this helps.
Thanks JLBorges and Duoas! It was just what I needed.
Topic archived. No new replies allowed.