Is it possible to sort arrays using preprocessor?

廉价感情. 提交于 2019-12-05 07:54:26

No, it is not possible. You cannot do string operations (other than concatenation) with the preprocessor. And you can't compare strings with template metaprograming, either.

[edit] What you could do is put your datastructure in a file that is meant to be preprocessed by an external build script (e.g. the unix "sort" utility), and then modify your makefile/project so that at build time, you generate a C file with the (sorted) initialized arrays

Do this.

  1. Put your giant array in a file.

  2. Sort the file with the built-in sort

  3. Write a small program to create C code from the file. A C program that writes C programs is fine. You can use Python and some of it's cool template packages to make this job simpler.

  4. Compile the remaining program consisting of the sorted file transformed into C code plus the rest of your program.

I don't think you can do it in the gcc preprocessor, never seen something that could do what you are looking for.

But you could write your own "preprocessor" in your favourite scripting language (python, perl, sed etc...) that would sort those values before gcc kicks in.

I can think of no possibility to use the preprocessor, but you can use a combination of sort and #include to achieve the desired effect:

Put just the values into a seperate file values.h with the sort key being in front (you will need to rearrange your struct sometype for this):

{"BOB", somevals, someothervals},
{"ALICE", somevals, someothervals},
{"TIM", somevals, someothervals},

In your Makefile, use the Unix command sort to sort that file into values_sorted.h:

sort < values.h > values_sorted.h

In your actual code, include the sorted file:

sometype S[] = {
#include "values_sorted.h"
};

The following worked for two and three elements:

// Experiment: static sort:

#define STATIC_SORT2(CMP, a, b)    CMP(a,b) <= 0 ?(a):(b), CMP(a,b) <= 0 ? (b):(a),
#define STATIC_SORT3(CMP, a, b, c) \
    (CMP(a,b) <= 0 && CMP(a,c) <= 0 ? (a) : \
     CMP(b,a) <= 0 && CMP(b,c) <= 0 ? (b) : \
     (c)), \
    (CMP(a,b) <= 0 && CMP(a,c) <= 0 ? ( CMP(b,c) <= 0 ? (b) : (c) ) : \
     CMP(b,a) <= 0 && CMP(b,c) <= 0 ? ( CMP(a,c) <= 0 ? (a) : (c) ) : \
     (CMP(a,b) <= 0 ? (a) : (b))), \
    (CMP(a,c) <= 0 && CMP(b,c) <= 0 ? (c) : \
     CMP(a,b) <= 0 && CMP(c,b) <= 0 ? (b) : \
     (a))


// Example:
// #define STATIC_INT_CMP(a,b) ((int)(a) - (int)(b))
// int sorted[] = { STATIC_SORT3(STATIC_INT_CMP, 2, 3, 1 } // gives { 1, 2, 3 }
// #define STATIC_INT_COCMP(a,b) ((int)(b) - (int)(a))
// int cosorted[] = { STATIC_SORT3(STATIC_INT_COCMP, 2, 3, 1 } // gives { 3, 2, 1 }

But I'd say that it is clear that this approach does not generalize to arbitrary sized arrays. I suppose it is not possible, but I still don't have a formal proof for this conjecture.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!