5

I'm looking for a function to sort file names by name including numbers. It must do a special processing for numbers in names (as standard file managers of Windows/MAC OSes does).

E.g. usual sort function by just name sorts in this order:

name1
name11
name2

I need my function to sort in the following order:

name1
name2
name11

Is there a some standard or well known/working function?

The way I will use it:

std::sort(names.begin(), names.end(), sortfn);

I can write it without very big problems but prefer standard solutions. However, failed to google them.

Alexander Dyagilev
  • 1,139
  • 1
  • 15
  • 43
  • 2
    What's the type of `names`. A `vector` of `std::string`s? – lubgr May 02 '19 at 14:19
  • Add 0's before every number you find, then sort, then remove 0's? This has lots of problems if 0's already exist, but what are the constraints of the problem? – Fantastic Mr Fox May 02 '19 at 14:20
  • lugbr, yep, it's a vector of std::string. May also be QStrings (Qt library)... – Alexander Dyagilev May 02 '19 at 14:23
  • These are arbitrary names of files. Any names (strings) a file can have. Including e.g. "123name456". – Alexander Dyagilev May 02 '19 at 14:26
  • 2
    AFAIK, C++ doesn't define such a *smart* comparison function, so you will have to write it. Its complexity depends on the required versatility. It will be rather easy if names have to start with alpha and numbers are the last part, harder if numbers and alpha may be interleaved in any way. – Serge Ballesta May 02 '19 at 14:28
  • Nope, it's not hard :) But i'm looking for a some standard/well known way. I'll post my solution as an answer if I fail to find one. – Alexander Dyagilev May 02 '19 at 14:29
  • lubgr, nope. Digits can be in any part of name. – Alexander Dyagilev May 02 '19 at 14:30
  • There are no special cases. Any name. Sort function just should work as the one used in Windows/MAC. Sorted lists should be the same. – Alexander Dyagilev May 02 '19 at 14:34
  • *"prefer standard solutions"* - that depends entirely on what you mean by "standard". The language + library standard does not define a comparator out of the box that does what you seek. To that end, the answer to the only question asked is: *no*. – WhozCraig May 02 '19 at 14:56
  • There is no "standard" solution. You can take inspiration from [UNIX sorting implementation for file versions](https://github.com/ekg/filevercmp). – BiagioF May 02 '19 at 15:19

0 Answers0