char & int array in dual sort
Hi ~
Can someone tell me if it is possible to do a dual sort on an array of chars and an array of int, double or float? Would you have to use two separate sorts? Really confused here.
I am trying to sort an array of 12 doubles (user input) so that the console output sorts it in descending order. The corresponding months should be printed as well.
Thanks for any help! Super lost on this one.
Re: char & int array in dual sort
Are you trying to sort both lists independently? Or do you want to have the second list be sorted like the first one? If I'm not being clear, say you have 'b', 'v', 'd', 'e' and 5, 1, 6, -1. Do you want them to be 'b', 'd', 'e', 'v' and -1, 1, 5, 6? Or like 'b', 'd', 'e', 'v' and 5, 6, -1, 1? For the former, just sort both separately. For the second, just sort the first array, but wherever you change the first array, change the second too. So, whenever you swap two elements in the first, swap in the second too.
Re: char & int array in dual sort
Quote:
Originally Posted by
Applellial
Hi ~
Can someone tell me if it is possible to do a dual sort on an array of chars and an array of int, double or float? Would you have to use two separate sorts? Really confused here.
Maybe your design is flawed. Think scalability and possibly future changes.
Use a struct of the various types and sort that instead of juggling two or more sorts around. What if you had 10 items tied to that array of characters? Are you going to write 10 separate sorts?
Code:
struct foo
{
int myInt;
double MyDouble;
char myChar;
// etc.
};
foo fooArray[10];
Then when you sort the array of foo by the myChar member, all other items ride along with it.
Regards,
Paul McKenzie
Re: char & int array in dual sort
I'd suggest you create a class (or struct) to hold the two components of each item, set up a single array containing these objects and then sort them using std::sort(). You'd need to define either operator< for that class or a predicate (comparison function or functor) in order to sort them. The sod::sort() sample code shows how to define a pedicate as either a function or functor.