Rewriting C++ template for C
Can anyone help me in rewriting this code from C++ to C... (it has templates... yeeee :)) Thank you.
template <class T>
void SWAP( T& t1, T& t2 )
{
T tmp=t1;
t1=t2;
t2=tmp;
}
and this one
template <class CMP, class Element>
void sh_qsort( Element* array, uint lo, uint hi )
{
some code...
}
and the sh_qsort is called like sh_qsort<TEST>( test_file, 0, 255 )
where TEST
is
struct TEST {
static int c( uint* A, int x, int y )
{
uint px = A[x];
uint py = A[y];
int r,s;
s = (px<py) ? SWAP(px,py),0x80000000 : 0;
byte* p = &f_buf[px];
byte* th = &f_buf[blocksize];
byte* q = &f_buf[py];
for(; (r=1,p<th) && ((r=(*p)-(*q))==0); p++,q++ );
return r^s;
}
static void s( uint* A, int x, int y )
{
SWAP( A[x], A[y] );
}
};
and how to rewrite this struct in c.
Simple and neat... HELP开发者_运维知识库 :)
Thank you!
Assuming sh_qsort()
actually is a quicksort implementation, all you need to do is refactor TEST::c()
into a comparison function as expected by qsort()
from stdlib.h
.
Going from compile-time generic code via templates to runtime-generic code via void *
normally carries a performance penalty, of which you could get rid of by using so-called 'X-macros' to simulate templates with the preprocessor. However, there's probably no need to bother: As TEST::c()
is sufficiently complex, it probably won't be inlined anyway, and you only have to pay for the use of the runtime-generic swaps performed by qsort()
.
Sorry guys, its the result of http://encode.ru/threads/1230-On-compressing-series-of-ones-and-zeroes. and I written the program which he's trying to translate. Anyway there's a more C-like implementation in http://ctxmodel.net/files/BWT.cpp
精彩评论