Dave's Brain

Browse - programming tips - shuffle cstringarray

Date: 2009oct11
Language: C/C++

Q.  How do I randomize the order (shuffle) an MFC CStringArray ?

A.  Here's a function that does it.

// Algorithm from Dr Dobbs, January 2000, page 113
void ShuffleCStringArray(CStringArray &a)
{
	CString		str;
	int			dest, src, n;

	srand((unsigned)time(NULL));
	n = a.GetSize();
	for (dest = n - 1; dest > 0; dest--)
	{
		src = rand() % (dest+1);

		// swap
		str = a[src];
		a[src] = a[dest];
		a[dest] = str;
	}
}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2012, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.