c语言模拟模板的函数的方法

 要求用C语言(不许用C++)编写一个函数,调用这个函数可以对一个数组进行排序,这个数组可以是整型、浮点型等。函数头(返回类型、函数名、参数列表)自定。

 

void mySort( void* p, int len, int dataType );

描述一下,首先将数组的指针传过来,因为C语言里面,任何类型的指针都可以赋值给空类型的

指针,所以这个赋值完全可以通过编译;第二个参数是数组的长度;第三个参数是这种数据类型

的长度,用来在mySort()里面将空指针指向别的数据类型的指针,然后再进行排序

C下面空指针可以和任何类型的指针互相赋值,而在C++里面禁止

 

利用宏

include "stdafx.h"

#include "stdio.h"

#define Sort(T, src, len) { /
   int i = 0; /
   while (i < len - 1) /
   { /
       int j = i + 1; /
       while (j < len) /
       { /
           if (src[j] < src[i]) /
           { /
               T t = src[j]; /
               src[j] = src[i]; /
               src[i] = t; /
           } /
           j++;/
       } /
       i++;/
   } /
} /

int main()
{
    int     int_array[8] = {9, 8, 5, 5, 3, 2, 1, 9};
    double  flt_array[8] = {9.5, 5.8, 5.4, 5.1, 3.9, 1.2, 0.1, 9.3};
    char    chr_array[8] = {'d', 'v', 'q', 'd', 't', 't', 'w', 'g'};

    int i = 0;

    Sort(int, int_array, 8);
    Sort(double, flt_array, 8);
    Sort(char, chr_array, 8);

    for (i = 0; i < 8; ++i)
        printf("%d ", int_array[i]);
    printf("/n");

    for (i = 0; i < 8; ++i)
        printf("%.2f ", flt_array[i]);
    printf("/n");

    i = -1;
    for (i = 0; i < 8; ++i)
        printf("%c ", chr_array[i]);
    printf("/n");

    return 0;
}

给一个不用传类型的,不过一定要多分配一个元素


#include "stdio.h"

#define Sort(src, len) { /
   int i = 0; /
   while (i < len - 1) /
   { /
       int j = i + 1; /
       while (j < len) /
       { /
           if (src[j] < src[i]) /
           { /
               src[len] = src[j]; /
               src[j] = src[i]; /
               src[i] = src[len]; /
           } /
           j++;/
       } /
       i++;/
   } /
} /

int main()
{
    /* 多分配一个空间,所以个数是 8, 大小是 8 + 1 == 9
    */
    int     int_array[9] = {9, 8, 5, 5, 3, 2, 1, 9};
    double  flt_array[9] = {9.5, 5.8, 5.4, 5.1, 3.9, 1.2, 0.1, 9.3};
    char    chr_array[9] = {'d', 'v', 'q', 'd', 't', 't', 'w', 'g'};

    int i = 0;

    Sort(int_array, 8);
    Sort(flt_array, 8);
    Sort(chr_array, 8);

    for (i = 0; i < 8; ++i)
        printf("%d ", int_array[i]);
    printf("/n");

    for (i = 0; i < 8; ++i)
        printf("%.2f ", flt_array[i]);
    printf("/n");

    for (i = 0; i < 8; ++i)
        printf("%c ", chr_array[i]);
    printf("/n");

    return 0;
}

 

#include "stdio.h"
#include "stdlib.h"

#define Sort(src, len) { /
   void* buf = malloc(sizeof(*src)); /
   int i = 0; /
   memcpy(buf, &src[len], sizeof(*src)); /
   while (i < len - 1) /
   { /
       int j = i + 1; /
       while (j < len) /
       { /
           if (src[j] < src[i]) /
           { /
               src[len] = src[j]; /
               src[j] = src[i]; /
               src[i] = src[len]; /
           } /
           j++;/
       } /
       i++;/
   } /
   memcpy(&src[len], buf, sizeof(*src)); /
   free(buf); /
} /

int main()
{
    int     int_array[8] = {9, 8, 5, 5, 3, 2, 1, 9};
    double  flt_array[8] = {9.5, 5.8, 5.4, 5.1, 3.9, 1.2, 0.1, 9.3};
    char    chr_array[8] = {'d', 'v', 'q', 'd', 't', 't', 'w', 'g'};

    int i = 0;

    Sort(int_array, 8);
    Sort(flt_array, 8);
    Sort(chr_array, 8);

    for (i = 0; i < 8; ++i)
        printf("%d ", int_array[i]);
    printf("/n");

    for (i = 0; i < 8; ++i)
        printf("%.2f ", flt_array[i]);
    printf("/n");

    for (i = 0; i < 8; ++i)
        printf("%c ", chr_array[i]);
    printf("/n");

    return 0;
}

 

还可以考虑用共用体,union.
参数加一个标志,这样做有点恶心,但是能做出来。
比如函数头:

typedef union {
    int           nValue;
    float         fValue;
    char          cValue;
}data_type;

typedef enum { int_value = 1, float_value =2, char_value = 3}value_flag;

void sort(data_type* data, value_flag flag) {
    switch (flag) {
        case int_value:
        // dosomething();
        break;
        case float_value:
        //doanother();
        break;
        case char_value:
        //doOther();
        break;
    }
}

另有一种比较高级的用法就是自己定义一些符号(中间语言,可以支持模板),然后自己写个小程序解析中间语言,就相当于用C++的文法写程序,用纯C编译器编译这些程序,而需要做的辅助工作就是解析中间语言。
最早的C++编译器就是这么做的。楼主可以参考一些怎么用纯C实现C++功能的代码。
可以重点参考GNU的代码,那里边就有用C实现模板,多态,以及异常处理的东西的。

 

应观众需求,帖个qsort

*-
 * Copyright (c) 1992, 1993
 *The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *This product includes software developed by the University of
 *California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)qsort.c8.1 (Berkeley) 6/4/93";
#endif
static const char rcsid[] =
"$Id: qsort.c,v 1.7 1997/02/22 15:03:14 peter Exp $";
#endif /* LIBC_SCCS and not lint */

#include <stdlib.h>

typedef int cmp_t __P((const void *, const void *));
static inline char*med3 __P((char *, char *, char *, cmp_t *));
static inline void swapfunc __P((char *, char *, int, int));

#define min(a, b)(a) < (b) ? a : b

/*
 * Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
 */
#define swapcode(TYPE, parmi, parmj, n) { /
long i = (n) / sizeof (TYPE); /
register TYPE *pi = (TYPE *) (parmi); /
register TYPE *pj = (TYPE *) (parmj); /
do { /
register TYPEt = *pi;/
*pi++ = *pj;/
*pj++ = t;/
        } while (--i > 0);/
}

#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || /
es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;

static inline void
swapfunc(a, b, n, swaptype)
char *a, *b;
int n, swaptype;
{
if(swaptype <= 1)
swapcode(long, a, b, n)
else
swapcode(char, a, b, n)
}

#define swap(a, b)/
if (swaptype == 0) {/
long t = *(long *)(a);/
*(long *)(a) = *(long *)(b);/
*(long *)(b) = t;/
} else/
swapfunc(a, b, es, swaptype)

#define vecswap(a, b, n) if ((n) > 0) swapfunc(a, b, n, swaptype)

static inline char *
med3(a, b, c, cmp)
char *a, *b, *c;
cmp_t *cmp;
{
return cmp(a, b) < 0 ?
       (cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
              :(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
}

void
qsort(a, n, es, cmp)
void *a;
size_t n, es;
cmp_t *cmp;
{
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
int d, r, swaptype, swap_cnt;

loop:SWAPINIT(a, es);
swap_cnt = 0;
if (n < 7) {
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
     pl -= es)
swap(pl, pl - es);
return;
}
pm = (char *)a + (n / 2) * es;
if (n > 7) {
pl = a;
pn = (char *)a + (n - 1) * es;
if (n > 40) {
d = (n / 8) * es;
pl = med3(pl, pl + d, pl + 2 * d, cmp);
pm = med3(pm - d, pm, pm + d, cmp);
pn = med3(pn - 2 * d, pn - d, pn, cmp);
}
pm = med3(pl, pm, pn, cmp);
}
swap(a, pm);
pa = pb = (char *)a + es;

pc = pd = (char *)a + (n - 1) * es;
for (;;) {
while (pb <= pc && (r = cmp(pb, a)) <= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pa, pb);
pa += es;
}
pb += es;
}
while (pb <= pc && (r = cmp(pc, a)) >= 0) {
if (r == 0) {
swap_cnt = 1;
swap(pc, pd);
pd -= es;
}
pc -= es;
}
if (pb > pc)
break;
swap(pb, pc);
swap_cnt = 1;
pb += es;
pc -= es;
}
if (swap_cnt == 0) {  /* Switch to insertion sort */
for (pm = (char *)a + es; pm < (char *)a + n * es; pm += es)
for (pl = pm; pl > (char *)a && cmp(pl - es, pl) > 0;
     pl -= es)
swap(pl, pl - es);
return;
}

pn = (char *)a + n * es;
r = min(pa - (char *)a, pb - pa);
vecswap(a, pb - r, r);
r = min(pd - pc, pn - pd - es);
vecswap(pb, pn - r, r);
if ((r = pb - pa) > es)
qsort(a, r / es, es, cmp);
if ((r = pd - pc) > es) {
/* Iterate rather than recurse to save stack space */
a = pn - r;
n = r / es;
goto loop;
}
/*qsort(pn - r, r / es, es, cmp);*/
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值