Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to sort a bunch of elements first by document name and then by the age of the people inside the document.

sort(vec.begin(), vec.end(), ltNames);

or can i change name into this? documentname+age and then just use ltNames?

I would get

agedpeople67
agedpeople68
agedpeople99
youngpeople1
youngpeople2
youngpeople3

would that work?
Posted
Updated 21-Feb-14 16:05pm
v2

Have you looked under the term "Radix sort"? This is the basis behind alphabetical sorting, and it sounds like you need to just have two sorts--one for alphabetical, then one for numeric.

The advantage of going for a Radix sort is that a good algorithm maintains the sort from the previous sort--in your case, the alphabetized sort must be maintained when you go with the age sort.

There is a nice looking C++ implementation here at Rosetta Code that you should be able to modify.

The implementation you are thinking of will probably fail for a good number of values. For example, if you have an agedpeople listing with ages of 1,2,10,20, your list will probably look like this:

agedpeople1
agedpeople10
agedpeople2
agedpeople20

which is not the correct order from what I understand.
 
Share this answer
 
It is quite common that one want to sort not only by a single, but multiple properties of an object. This can even be done in a single sorting run. The trick is to use an appropriate compare function.

The compare function tells the sorting algorithm, whether one element comes before or after a particular other element. In your case that means that you should implement a compare function that ranks

aaa1 before aaa2
aaa1 before aaa10
aaa2 before aaa10
...
aaa99 before bbb1

and so forth. To implement such a compare function you should put your two keys into a structure (instead of concattenating them to a string). For example:

C++
struct SortKey
{
   string docName;
   int    age;
};

Then create a vector of your sort keys, something like:
C++
    vector<sortkey> keys;
</sortkey>

And finally you need the compare function, which would look like:
C++
bool MyCompFunction (const SortKey& a, const SortKey& b)
{
    return a.docName < b.docName || a.docName == b.docName && a.age < b.age;
}

In other words: Element a comes before b if either its docName is smaller than b's, or if the docNames are equal and the a's age is smaller than b's.

Now you can call sort on your vector and by specifying your own compare function:
C++
sort (keys.begin(), keys.end(), MyCompFunction);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900