Sign in to follow this  
Jarwulf

arbitrary sort function

Recommended Posts

Hi, does anyone know of a C++ sort algorithm or library that can take input of a bunch of rows and sort rows by an arbitrary defined order of such as

 

ie sort rows by first column in this order (boba bobc bobe bobx) etc?

Edited by Jarwulf

Share this post


Link to post
Share on other sites

Std::sort is designed for this - the 3rd parameter is the ordering/comparison function to use.

**sorry no example, I'm posting from my phone, google should have some ;)**

 

I see plenty of examples with simple stuff like arrays but I don't really see examples of how std:sort can work on arranging rows of a big input file let alone arranging them based on the value of a specific column in a predefined order ie (Z, X, A, B) .

Share this post


Link to post
Share on other sites
Sorting is typically done in memory, and Hodgman's answer is perfectly fine.

If you are interested in sorting files that are so large that they don't fit in memory, look up external sorting. But I very much doubt that's what you want

Share this post


Link to post
Share on other sites
To clarify, it's not a special sorting algorithm you want, virtually all of them can do this. std::sort or std::stable_sort are fine for this.

What you want is special comparison and exchanging functionality. Even then, this sort of thing is not that uncommon.
In order to have it run-time configurable, you may be best to declare a comparator that takes a list of column IDs in its constructor, and whose () operator uses that accordingly. If you don't need to change the order the columns are sorted by at run-time then its even easier, and a very common thing to do.
Then it's just a matter of ensuring it swaps 'rows' correctly, probably via writing a custom swap function for your 'row' class. Edited by iMalc

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this