views:

175

answers:

4

For sorting item names, I want to support numbers correctly. i.e. this:

1 Hamlet
2 Ophelia
...
10 Laertes

instead of

1 Hamlet
10 Laertes
2 Ophelia
...

Does anyone know of a comparison functor that already supports that?
(i.e. a predicate that can be passed to std::sort)

I basically have two patterns to support: Leading number (as above), and number at end, similar to explorer:

Dolly
Dolly (2)
Dolly (3)

(I guess I could work that out: compare by character, and treat numeric values differently. However, that would probably break unicode collaiton and whatnot)

+5  A: 

That's called alphanumeric sorting.
Check out this link: The Alphanum Algorithm

Nick D
Thanks! It doesn't collate segments (rather, compare char-by-char), and doesn't correctly handle numbers exceeding unsigned long, but it's a good drop-in replacement.
peterchen
+1  A: 

There's one on the Boost Cookbook site. It uses the Boost Regex library, but should be simple enough to convert to any other regex library.

http://www.boostcookbook.com/Recipe%3A/1235053

KayEss
thanks - I want to avoid the dependency on boost::regex for now. Anyway, the site has definitely interesting snippets.
peterchen
+1  A: 

There's this article Sorting for Humans : Natural Sort Order by Jeff.

anno
A: 

i think u can use a pair object and then make vector > and then sort this vector. Pairs are compared based on their first elements. So, this way you can get the sort you desire.

ajay