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

转载 2007年09月23日 19:02:00

 要求用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);*/
}

 

相关文章推荐

c语言模拟实现栈的模板化

对于写过表达式解析的同学一定不会陌生,我们需要两个栈,一个是符号栈(char),一个是操作数栈(int).  经典的数据结构书中的栈,类型是定死了的。 所以能够实现一个栈,自己指定类型,想必编写接下...

Win32 SDK函数MessageBox的模拟实现(C语言版)

版本一:对于使用“掩码”传递参数的方法,简单的实现思路: #include #define MB_OK 0x00000000 #define MB_OKCANCE...

模拟实现C语言中的库函数atoi

atoi() 函数用来将字符串转换成整数(int),其原型为: int atoi (const char * str);【函数说明】atoi() 函数会扫描参数 str 字符串,跳过前面的空白字符(...

C语言:模拟实现strlen、strcpy、strcmp、strReverse、strcat函数

环境: Windows8,Visual Studio 2013 语言: C语言什么是C语言里的字符串?字符串或串(String)是由数字、字母、下划线组成的一串字符。一般记为s=“a1a2···a...

【C语言】模拟实现strcpy、strcat、strcmp函数

strcpy、strcat、strcmp这三个库函数是初级学习阶段经常写到的三个库函数,也是一些大公司比较喜欢出的面试题。今天,就尝试用my_strcpy、my_strcat、my_strcmp这三个...

【C语言】模拟实现strncpy、strncat、strncmp函数

【C语言】模拟实现strncpy、strncat、strncmp函数

c语言模拟库函数strlen、strcpy、strcmp.

strlen()函数功能是计算字符串中字符个数,而字符本身就是一个字符数组,只不过末尾以‘\0’结束。 strcpy()函数是把从psrc地址开始且含有NULL结束符的字符串复制到以pdest开始...

娱乐,C语言模拟C++虚函数多态性

看有感,原来C语言可以这样玩。。仔细想想,C++不也是在汇编层面上的封装么。膜拜这些语言设计者,深谙计算机科学的精髓,真是长见识了。 本文只是简单模拟下多态,大体上就是C++的虚函数表机制,并没有考...

C语言 string及memcpy,memmove函数的模拟实现

模拟实现部分字符串操作函数及内存拷贝函数

【C语言】模拟实现strncpy strncat strncmp strchr strrchr函数

模拟实现strncpy strncat strncmp strchr strrchr函数!
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)