Shuffle a Char Array

Feb 18, 2011 at 2:26pm
All,

I'm having trouble trying to find a way to sort a char array, i've created the array as per below:

ColourArray[0] = "orange";
ColourArray[1] = "green";
ColourArray[2] = "white";
ColourArray[3] = "purple";
ColourArray[4] = "yellow";
ColourArray[5] = "pink";

There seems to be many different ways to sort int arrays but not char (I've tried change the types over to char but did not work)
Could someone possibly point me in the right direction.
Thanks

C.
Feb 18, 2011 at 2:29pm
Assuming by "char array", you meant a vector<string> (if you didn't, you do now):

sort(ColourArray.begin(),ColourArray.end());
Feb 18, 2011 at 2:31pm
If it's a raw array, you can still sort it by passing the equivalent values:

sort(ColourArray, ColourArray + size);
Feb 18, 2011 at 2:43pm
Only if it's a std::string array, though.
Feb 18, 2011 at 2:53pm
This is how I am creating the array

1
2
3
4
5
6
7
8
char *ColourArray[5];

ColourArray[0] = "orange";
ColourArray[1] = "green";
ColourArray[2] = "white";
ColourArray[3] = "purple";
ColourArray[4] = "yellow";
ColourArray[5] = "pink";


I'm coming from a VB.Net background so all this is very new to me (like only been at this a couple of days)

I've tried adding the sort and the
#include <algorithm>
but my sort still says undefined.
Feb 18, 2011 at 3:14pm
You shouldn't use C strings and raw arrays in C++ unless you have to, especially if you're just learning the language. I'd do this instead:

1
2
3
4
5
6
7
std::vector<std::string> strings;
strings.push_back("orange");
strings.push_back("green");
strings.push_back("white");
strings.push_back("purple");
strings.push_back("yellow");
strings.push_back("pink");

If you're not familiar with vectors and strings, look up this site's reference.
Feb 18, 2011 at 4:05pm
Thanks everyone, I'll take a look and try this approach.

Much appreciated.

C.
Topic archived. No new replies allowed.