0

Consider we have an array of strings:

static constexpr char *sCommands[] = {
    "AAA",
    "CCC",
    "BBB",
    "DDD",
    ...
};

Can we get it sorted at compile time (or get another sorted array) without using std? Template is allowed.

Edit

Some background: This list will be binary-searched so it has to be sorted. The intention for doing the compile-time sorting is: There will be a lot of macros wrapping these items in this list and it's hard to maintain.

For example:

static constexpr char *sCommands[] = {
#if FEATURE_1
    "AAA",
#endif
#if FEATURE_2
    "BBB",
#endif
#if FEATURE_1
    "CCC",
#endif
#if FEATURE_2
    "DDD",
#endif
    ...
};

In real cases, this is more complex with nested macros, which makes the code hard to read and maintain.

I would be better if we can put the items under the macros:

static constexpr char *sCommands[] = {
#if FEATURE_1
    "AAA",
    "CCC",
#endif
#if FEATURE_2
    "BBB",
    "DDD",
#endif
    ...
};
oos1111
  • 43
  • 8
  • 4
    It'd be far easier to sort this in your text editor. What problem are you trying to solve? – 1201ProgramAlarm May 16 '21 at 15:16
  • I'd suggest copying the contents of the array out to a separate .txt file, then doing `sort sorted_file.txt`, and then inserting the contents of `sorted_file.txt` back into your .cpp file. – Jeremy Friesner May 16 '21 at 18:54
  • Thanks for helping :) I made an update for the intention of doing this. – oos1111 May 17 '21 at 00:51
  • You can write your own `constexpr` sort algorithm. Not easy though. – Fantastic Mr Fox May 17 '21 at 00:51
  • 1
    Does this answer your question? [constexpr initialization of array to sort contents](https://stackoverflow.com/questions/19559808/constexpr-initialization-of-array-to-sort-contents) – Fantastic Mr Fox May 17 '21 at 00:53
  • Just an aside - that you might want to address in production -: your `sCommands` entries are modifiable. https://godbolt.org/z/EGYjaoafE – zyndor Aug 19 '23 at 01:27

0 Answers0