-
March 4th, 2011, 10:29 PM
#1
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.
-
March 4th, 2011, 11:10 PM
#2
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.
-
March 5th, 2011, 12:38 AM
#3
Re: char & int array in dual sort
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
-
March 5th, 2011, 12:41 AM
#4
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.
I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.
This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|