Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to sort arrays using preprocessor?

I have a number of very long arrays. No run-time sort is possible. It is also time consuming to sort them manually. Moreover, new elements can be added in any order later, so I would like to sort them by value using C preprocessor or maybe there is any compilers flag (GCC)?

For example:

sometype S[] = {
  {somevals, "BOB", someothervals},
  {somevals, "ALICE", someothervals},
  {somevals, "TIM", someothervals},
}

must be sorted so:

sometype S[] = {
   {somevals, "ALICE", someothervals},
   {somevals, "BOB", someothervals},
   {somevals, "TIM", someothervals},
}


SOLVED

Ok, here is my solution:

  1. Manually copy&paste each array into a temporary file called tobesorted.c
  2. Sort it by 2nd column: sort -b -i --key=2 tobesorted.c
  3. Copy&paste output back into original file.

Actually, it would be nice to have some possibility to call "sort" directly from the preprocessor (I had a hope that at least GCC somehow support such features, but it seems that it doesn't).

like image 801
psihodelia Avatar asked Apr 13 '10 11:04

psihodelia


People also ask

Can sorting be done on array?

There are many ways by which the array can be sorted in ascending order, like: Selection Sort. Binary Sort. Merge Sort.

How do you sort data in an array?

The formula =SORT(A3:B17) uses the default "sort by" and "sort order" settings; thus, the list is sorted in alphabetical order. The syntax for the new SORT function is =SORT(array, [sort_index], [sort_order], [by_column]). The first argument identifies the array to be sorted. All the other arguments are optional.

Can you sort an array in CPP?

In programming language, sorting is a basic function which is applied to data to arrange these data is ascending or descending data. In C++ program, there is a function std::sort() for sorting the array.


2 Answers

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.

like image 52
S.Lott Avatar answered Sep 25 '22 07:09

S.Lott


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

like image 45
Virgil Avatar answered Sep 22 '22 07:09

Virgil