使用纯C语言定义通用型数据结构的方法和示例

这篇具有很好参考价值的文章主要介绍了使用纯C语言定义通用型数据结构的方法和示例。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

前言

最近一段时间在复习数据结构和算法,用的C语言,不得不说,不学个高级语言再回头看C语言根本不知道C语言的强大和完美,不过相比之下也有许多不便利的地方,尤其是以下两个方面:

  • 没有异常处理机制
  • 没有泛型

其中第一方面之前就解决了,详情请看在C语言中实现类似面向对象语言的异常处理机制,今天下午有空来实现一下泛型。不得不说,通过异常处理机制和泛型的实现,既让我C语言使用的得心应手,又让我对高级语言的设计有了亲身般体验。

以实现优先队列来描述实现思想

首先C语言本身不支持泛型,这意味着实现泛型有以下两个困难(解决这两个困难也就意味着成功):

  • ①:类型信息在编译前就已经确定了
  • ②:类型信息不能像参数一样传递

有了目标就轻松多了,于是我立刻就想到了函数的可变参数<stdarg.h>,请看下面的DEMO:

PackagingTypeList intBatchValueOf(int size, ...) {
    PackagingTypeList list = calloc(size, sizeof(PackagingType *));
    va_list argList;
    va_start(argList, size);
    for (int i = 0; i < size; ++i) {
        union PackagingType *pack = malloc(sizeof(PackagingType));
        pack->intValue = va_arg(argList, int);
        *(list + i) = pack;
    }
    va_end(argList);
    return list;
}

在使用va_arg取可变参数时我们确实直接将int类型作为参数传递了,这就意味着困难②克服了,那么困难①呢?于是我继续研究,我发现函数的参数存储在一个GCC内置的数据结构中:

typedef struct {
       void *__stack;					/* __stack 记录下一个匿名栈参数的存储位置, 随着va_arg的调用可能变化 */
       void *__gr_top;					/* __gr_top 记录最后一个匿名通用寄存器参数的尾地址, 其不随va_arg调用变化 */
       void *__vr_top;					/* __vr_top 记录最后一个匿名浮点寄存器参数的尾地址, 其不随va_arg调用变化 */
       int   __gr_offs;				    /* __gr_offs 记录下一个匿名通用寄存器参数到__gr_top的偏移(负数),随着va_arg的调用可能变化 */
       int   __vr_offs;					/* __vr_offs 记录下一个匿名浮点寄存器参数到__vr_top的偏移(负数),随着va_arg的调用可能变化 */
} __builtin_va_list;

这就意味着要想克服困难①就必须得到编译器的支持,显然这是不可能的,于是我果断放弃了,但困难②的克服给我了灵感,va_arg是一个宏定义,强大的预处理器赋予了C语言元编程的能力,这就是我想到的第一种方法:

  • 克服困难①:使用宏定义在编译时定义可以存储指定类型的优先队列,
  • 克服困难②:使用带参数的宏传递类型信息

于是第一种方案诞生了:

#define PriorityQueueNode(TYPE)                                                     \
{                                                                                   \
    typedef struct PriorityQueueNode_##TYPE{                                        \
        TYPE data;                                                                  \
        struct PriorityQueueNode *next;                                             \
        struct PriorityQueueNode *prior;                                            \
    }PriorityQueueNode_##TYPE;                                                      \
}while(false)

#define priorityQueueEnQueue(TYPE)                                                  \
{                                                                                   \
    void priorityQueueEnQueue_##TYPE(struct PriorityQueue_##TYPE queue,TYPE data){  \
        ...                                                                       \
    }                                                                               \
}while(false)

#define PriorityQueue(TYPE, NAME)                                                   \
{                                                                                   \
    PriorityQueueNode(TYPE);                                                        \
    priorityQueueEnQueue(TYPE)                                                      \
    PriorityQueueNode_##TYPE head={.next=NULL,.prior=NULL};                         \
    struct PriorityQueue_##TYPE{                                                    \
        PriorityQueueNode *front;                                                   \
        PriorityQueueNode *rear;                                                    \
        void (* priorityQueueEnQueue)(struct PriorityQueue_##TYPE,TYPE);            \
    } NAME={                                                                        \
       .front=&head,                                                                \
       .rear=&head                                                                  \
       .priorityQueueEnQueue=priorityQueueEnQueue_##TYPE                            \
    };                                                                              \
}while(false)

不过还没等写完我就放弃了,因为这太不优雅了,这其实和单独为每种类型定义一个优先队列没什么区别,于是我又想到了void*指针,这就是我想到的第二个方法,也是最终实现的方法:

  • 克服困难①:使用void*指针存储任意数据类型的指针,实际存储数据的空间由调用者分配
  • 克服困难②:在数据结构内部需要类型信息的地方通过传入的函数完成,这个函数也由调用者提供
//PriorityQueue.h

#ifndef INC_2023_PRIORITYQUEUE_H
#define INC_2023_PRIORITYQUEUE_H

#include "../../../util/Util.h"

typedef struct PriorityQueueNode PriorityQueueNode;
typedef struct PriorityQueue *PriorityQueue;

/**
 * 构造带头结点的优先队列
 * @param compare
 * @return
 */
PriorityQueue priorityQueueConstructor(int (*compare)(void *, void *)) throws NULL_POINTER_EXCEPTION;

/**
 * 销毁优先队列
 * @param queue
 */
void priorityQueueFinalize(PriorityQueue queue) throws NULL_POINTER_EXCEPTION;

/**
 * 优先队列是否为空
 * @param queue
 * @return
 */
bool priorityQueueIsEmpty(PriorityQueue queue) throws NULL_POINTER_EXCEPTION;

/**
 * 入队
 * @param queue
 * @param element
 */
void priorityQueueEnQueue(PriorityQueue queue, void *element) throws NULL_POINTER_EXCEPTION;

/**
 * 出队
 * @param queue
 * @return
 */
void *priorityQueueDeQueue(PriorityQueue queue) throws NULL_POINTER_EXCEPTION;


#endif //INC_2023_PRIORITYQUEUE_H
//PriorityQueue.c

#include "PriorityQueue.h"

struct PriorityQueueNode {
    void *data;
    PriorityQueueNode *next;
    PriorityQueueNode *prior;
};

struct PriorityQueue {
    PriorityQueueNode *front;
    PriorityQueueNode *rear;

    int (*compare)(void *, void *);
};

/**
 * 构造带头结点的优先队列
 * @param compare
 * @return
 */
PriorityQueue priorityQueueConstructor(int (*compare)(void *, void *)) throws NULL_POINTER_EXCEPTION {
    if (compare == NULL) {
        throw Error(NULL_POINTER_EXCEPTION, "比较函数不能为空");
    }
    PriorityQueue queue = malloc(sizeof(struct PriorityQueue));
    //头结点
    queue->front = queue->rear = malloc(sizeof(PriorityQueueNode));
    queue->front->next = NULL;
    queue->front->prior = NULL;
    queue->compare = compare;
    return queue;
}

/**
 * 销毁优先队列
 * @param queue
 */
void priorityQueueFinalize(PriorityQueue queue) throws NULL_POINTER_EXCEPTION {
    if (queue == NULL) {
        throw Error(NULL_POINTER_EXCEPTION, "优先队列不能为空");
    }
    for (; !priorityQueueIsEmpty(queue);) {
        priorityQueueDeQueue(queue);
    }
    free(queue->front);
    free(queue);
}

/**
 * 优先队列是否为空
 * @param queue
 * @return
 */
bool priorityQueueIsEmpty(PriorityQueue queue) throws NULL_POINTER_EXCEPTION {
    if (queue == NULL) {
        throw Error(NULL_POINTER_EXCEPTION, "优先队列不能为空");
    }
    if (queue->front == queue->rear) {
        return true;
    } else {
        return false;
    }
}

/**
 * 入队
 * @param queue
 * @param element
 */
void priorityQueueEnQueue(PriorityQueue queue, void *element) throws NULL_POINTER_EXCEPTION {
    if (queue == NULL) {
        throw Error(NULL_POINTER_EXCEPTION, "优先队列不能为空");
    }
    PriorityQueueNode *node = malloc(sizeof(PriorityQueueNode));
    node->data = element;
    //如果新加入元素优先级比队尾元素优先级小则直接插入队尾,否则就遍历优先队列找到合适的插入位置
    if (priorityQueueIsEmpty(queue) || queue->compare(queue->rear->data, node->data) > 0) {
        node->next = NULL;
        node->prior = queue->rear;
        queue->rear->next = node;
        queue->rear = node;
    } else {
        for (PriorityQueueNode *temp = queue->front->next; temp != NULL; temp = temp->next) {
            if (queue->compare(temp->data, node->data) <= 0) {
                node->next = temp;
                node->prior = temp->prior;
                temp->prior->next = node;
                temp->prior = node;
                break;
            }
        }
    }
}

/**
 * 出队
 * @param queue
 * @return
 */
void *priorityQueueDeQueue(PriorityQueue queue) throws NULL_POINTER_EXCEPTION {
    if (queue == NULL) {
        throw Error(NULL_POINTER_EXCEPTION, "优先队列不能为空");
    }
    if (!priorityQueueIsEmpty(queue)) {
        PriorityQueueNode *node = queue->front->next;
        void *data = node->data;
        if (queue->rear == node) {
            queue->rear = queue->front;
            queue->front->next = NULL;
        } else {
            queue->front->next = node->next;
            node->next->prior = queue->front;
        }
        free(node);
        return data;
    } else {
        return NULL;
    }
}

基本类型的包装类型

为了方便基本类型指针的获取,我定义了基本类型的包装类型:

//PackagingType.h

#ifndef DSA_PACKAGINGTYPE_H
#define DSA_PACKAGINGTYPE_H

#include <stdbool.h>
#include <stdarg.h>
#include <stdlib.h>

typedef union PackagingType PackagingType, **PackagingTypeList;

int getIntValue(void *element);

float getFloatValue(void *element);

double getDoubleValue(void *element);

char getCharValue(void *element);

bool getBoolValue(void *element);

PackagingType *intValueOf(int value);

PackagingTypeList intBatchValueOf(int size, ...);

PackagingType *floatValueOf(float value);

PackagingTypeList floatBatchValueOf(int size, ...);

PackagingType *doubleValueOf(double value);

PackagingTypeList doubleBatchValueOf(int size, ...);

PackagingType *charValueOf(char value);

PackagingTypeList charBatchValueOf(int size, ...);

PackagingType *boolValueOf(bool value);

PackagingTypeList boolBatchValueOf(int size, ...);

#endif //DSA_PACKAGINGTYPE_H

//PackagingType.c

union PackagingType {
    int intValue;
    float floatValue;
    double doubleValue;
    char charValue;
    bool boolValue;
};

int getIntValue(void *element) {
    return ((PackagingType *) element)->intValue;
}

float getFloatValue(void *element) {
    return ((PackagingType *) element)->floatValue;
}

double getDoubleValue(void *element) {
    return ((PackagingType *) element)->doubleValue;
}

char getCharValue(void *element) {
    return ((PackagingType *) element)->charValue;
}

bool getBoolValue(void *element) {
    return ((PackagingType *) element)->boolValue;
}

PackagingType *intValueOf(int value) {
    union PackagingType *pack = malloc(sizeof(PackagingType));
    pack->intValue = value;
    return pack;
}

PackagingTypeList intBatchValueOf(int size, ...) {
    PackagingTypeList list = calloc(size, sizeof(PackagingType *));
    va_list argList;
    va_start(argList, size);
    for (int i = 0; i < size; ++i) {
        union PackagingType *pack = malloc(sizeof(PackagingType));
        pack->intValue = va_arg(argList, int);
        *(list + i) = pack;
    }
    va_end(argList);
    return list;
}

PackagingType *floatValueOf(float value) {
    union PackagingType *pack = malloc(sizeof(PackagingType));
    pack->floatValue = value;
    return pack;
}

PackagingTypeList floatBatchValueOf(int size, ...) {
    PackagingTypeList list = calloc(size, sizeof(PackagingType *));
    va_list argList;
    va_start(argList, size);
    for (int i = 0; i < size; ++i) {
        union PackagingType *pack = malloc(sizeof(PackagingType));
        pack->intValue = va_arg(argList, double);
        *(list + i) = pack;
    }
    va_end(argList);
    return list;
}

PackagingType *doubleValueOf(double value) {
    union PackagingType *pack = malloc(sizeof(PackagingType));
    pack->doubleValue = value;
    return pack;
}

PackagingTypeList doubleBatchValueOf(int size, ...) {
    PackagingTypeList list = calloc(size, sizeof(PackagingType *));
    va_list argList;
    va_start(argList, size);
    for (int i = 0; i < size; ++i) {
        union PackagingType *pack = malloc(sizeof(PackagingType));
        pack->intValue = va_arg(argList, double);
        *(list + i) = pack;
    }
    va_end(argList);
    return list;
}

PackagingType *charValueOf(char value) {
    union PackagingType *pack = malloc(sizeof(PackagingType));
    pack->charValue = value;
    return pack;
}

PackagingTypeList charBatchValueOf(int size, ...) {
    PackagingTypeList list = calloc(size, sizeof(PackagingType *));
    va_list argList;
    va_start(argList, size);
    for (int i = 0; i < size; ++i) {
        union PackagingType *pack = malloc(sizeof(PackagingType));
        pack->intValue = va_arg(argList, int);
        *(list + i) = pack;
    }
    va_end(argList);
    return list;
}

PackagingType *boolValueOf(bool value) {
    union PackagingType *pack = malloc(sizeof(PackagingType));
    pack->boolValue = value;
    return pack;
}

PackagingTypeList boolBatchValueOf(int size, ...) {
    PackagingTypeList list = calloc(size, sizeof(PackagingType *));
    va_list argList;
    va_start(argList, size);
    for (int i = 0; i < size; ++i) {
        union PackagingType *pack = malloc(sizeof(PackagingType));
        pack->intValue = va_arg(argList, int);
        *(list + i) = pack;
    }
    va_end(argList);
    return list;
}

比较函数

通过创建多个数据结构发现,在数据结构内部用到的往往是比较函数,因此,我把常用的比较函数都定义了一下:

//Comparable.h

#ifndef DSA_COMPARABLE_H
#define DSA_COMPARABLE_H

#include "../packaging-type/PackagingType.h"

extern int (*intCompare)(void *, void *);

extern int (*intPackCompare)(void *, void *);

extern int (*floatCompare)(void *, void *);

extern int (*floatPackCompare)(void *, void *);

extern int (*doubleCompare)(void *, void *);

extern int (*doublePackCompare)(void *, void *);

extern int (*charCompare)(void *, void *);

extern int (*charPackCompare)(void *, void *);

#endif //DSA_COMPARABLE_H
//Comparable.c

#include "Comparable.h"

int intComp(void *a, void *b) {
    return *((int *) a) - *((int *) b) > 0;
}

int intPackComp(void *a, void *b) {
    return getIntValue(a) - getIntValue(b) > 0;
}

int floatComp(void *a, void *b) {
    return *((float *) a) - *((float *) b) > 0;
}

int floatPackComp(void *a, void *b) {
    return getFloatValue(a) - getFloatValue(b) > 0;
}

int doubleComp(void *a, void *b) {
    return *((double *) a) - *((double *) b) > 0;
}

int doublePackComp(void *a, void *b) {
    return getDoubleValue(a) - getDoubleValue(b) > 0;
}

int charComp(void *a, void *b) {
    return *((char *) a) - *((char *) b) > 0;
}

int charPackComp(void *a, void *b) {
    return getCharValue(a) - getCharValue(b) > 0;
}

int (*intCompare)(void *, void *) =intComp;

int (*intPackCompare)(void *, void *) =intPackComp;

int (*floatCompare)(void *, void *) =floatComp;

int (*floatPackCompare)(void *, void *) =floatPackComp;

int (*doubleCompare)(void *, void *) =doubleComp;

int (*doublePackCompare)(void *, void *) =doublePackComp;

int (*charCompare)(void *, void *) =charComp;

int (*charPackCompare)(void *, void *) =charPackComp;

演示

首先看一个基本类型的例子:

#include "util/Util.h"
#include "linear-structure/queue/priority-queue/PriorityQueue.h"

int main() {
    PackagingTypeList list = intBatchValueOf(4, 1, 2, 3, 4);
    PriorityQueue queue = priorityQueueConstructor(intPackCompare);
    for (int i = 0; i < 4; ++i) {
        priorityQueueEnQueue(queue, *(list + i));
    }
    while (!priorityQueueIsEmpty(queue)) {
        printf("%d", getIntValue(priorityQueueDeQueue(queue)));
    }
    return 0;
}

使用纯C语言定义通用型数据结构的方法和示例,c语言,数据结构,开发语言,优先队列,void指针

再看一个结构类型的例子:

#include "util/Util.h"
#include "linear-structure/queue/priority-queue/PriorityQueue.h"

struct Student {
    int age;
    char *name;
};

int studentCompare(void *a, void *b) {
    return ((struct Student *) a)->age - ((struct Student *) b)->age > 0;
}

int main() {
    struct Student a = {.age=18, .name="张三"}, b = {.age=28, .name="李四"};
    PriorityQueue queue = priorityQueueConstructor(studentCompare);
    priorityQueueEnQueue(queue, &a);
    priorityQueueEnQueue(queue, &b);
    while (!priorityQueueIsEmpty(queue)) {
        printf("%s,", ((struct Student *) priorityQueueDeQueue(queue))->name);
    }
    return 0;
}

使用纯C语言定义通用型数据结构的方法和示例,c语言,数据结构,开发语言,优先队列,void指针

最后看一个抛异常的例子:

#include "util/Util.h"
#include "linear-structure/queue/priority-queue/PriorityQueue.h"

struct Student {
    int age;
    char *name;
};

int studentCompare(void *a, void *b) {
    return ((struct Student *) a)->age - ((struct Student *) b)->age > 0;
}

int main() {
    struct Student a = {.age=18, .name="张三"}, b = {.age=28, .name="李四"};
    PriorityQueue queue = priorityQueueConstructor(studentCompare);
    priorityQueueEnQueue(queue, &a);
    priorityQueueEnQueue(queue, &b);
    try {
        while (!priorityQueueIsEmpty(queue)) {
            printf("%s,", ((struct Student *) priorityQueueDeQueue(NULL))->name);//change to NULL
        }
    } catch(NULL_POINTER_EXCEPTION) {
        stdErr();
    }

    return 0;
}

使用纯C语言定义通用型数据结构的方法和示例,c语言,数据结构,开发语言,优先队列,void指针文章来源地址https://www.toymoban.com/news/detail-703579.html

总结

  • 第一种方法类似于C++的方式
  • 第二种方法类似于Java的方式

到了这里,关于使用纯C语言定义通用型数据结构的方法和示例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 支持标准OPS接口,通用型RK3568工控板上新!

    HD-RK3568-OPS主板基于HD-RK3568-CORE 工业级核心板设计,搭载1.8GHz主频的高性能ARM处理器,适用于工业现场应用需求。主板支持标准OPS接口、支持前后HDMI双路输出,具有即插即用、操作简单的特点,亦适用于数字标牌、自助终端、教育一体机等应用场景。 ​ 主要功能包括:  

    2024年04月17日
    浏览(24)
  • 阿里云服务器共享型、计算型和通用型有什么区别?

    阿里云服务器的CPU种类有很多,当阿里云搞活动的时候,往往会有共享型、计算型、通用型这几款,那么他们之间有什么区别呢? 共享型: 共享型目前常见的型号是共享标准型s6和共享计算型n4。 共享型产品采用非绑定CPU调度模式。每个vCPU会被随机分配到任何空闲CPU超线程

    2024年02月12日
    浏览(33)
  • 华为云RDS通用型(x86) vs 鲲鹏(ARM)架构的性能对比

    之前,我们对比了阿里云RDS的经济版(ARM)与x86版的性价比,这次我们来看看华为云的RDS MySQL的“通用型”(x86)与“鲲鹏通用增强型”(ARM)版本的情况如何。 这里依旧选择了用户较为常用的4c16g的规格进行测试,测试工具使用了sysbench的oltp_read_write模型进行测试。配置参数与选

    2024年02月03日
    浏览(29)
  • 性能测评:阿里云服务器ECS通用型g8i实例CPU内存安全存储

    阿里云服务器ECS通用型实例规格族g8i采用2.7 GHz主频的Intel Xeon(Sapphire Rapids) Platinum 8475B处理器,3.2 GHz睿频,g8i实例采用阿里云全新CIPU架构,可提供稳定的算力输出、更强劲的I/O引擎以及芯片级的安全加固。阿里云百科分享阿里云服务器ECS通用型g8i实例CPU计算性能、存储、网络

    2024年02月12日
    浏览(45)
  • 阿里云云服务器最新价格表(第六代计算型c6、通用型g6和内存型r6)

    目前阿里云第六代云服务器有计算型c6、通用型g6和内存型r6实例。计算型c6实例有2核4G、4核8G、8核16G配置可选,主要适用于网站应用、批量计算、视频编码等场景。通用型g6实例有2核8G、4核16G、8核32G配置可选,适用于各种类型的企业级应用,网站和游戏服务器等场景。内存型

    2024年02月03日
    浏览(39)
  • C语言自定义数据类型(一)定义和使用结构体变量

    C 语言提供了一些由系统已定义好的数据类型,如:int,float,char  等,用户可以在程序中用它们定义变量,解决一般的问题。 但是人们要处理的问题往往比较复杂,只有系统提供的类型还不能满足应用的要求,C语言允许用户根据需要自己建立一些数据类型,并用它来定义变

    2024年02月02日
    浏览(33)
  • C语言自定义数据类型(二)使用结构体数组

    一个结构体变量中可以存放一组有关联的数据(如一个学生的学号、姓名、成绩等数据)。如果有 10 个学生的数据需要参加运算,显然应该用数组,这就是结构体数组。结构体数组与以前介绍过的数值型数组的不同之处在于每个数组元素都是一个结构体类型的数据,它们都分别

    2024年01月19日
    浏览(29)
  • 【C语言】【数据结构】自定义类型:结构体

    这是一篇对结构体的详细介绍,这篇文章对结构体声明、结构体的自引用、结构体的初始化、结构体的内存分布和对齐规则、库函数offsetof、以及进行内存对齐的原因、如何修改默认对齐数、结构体传参进行介绍和说明。                  ✨  猪巴戒 :个人主页✨      

    2024年02月05日
    浏览(23)
  • C语言自定义数据类型(三)结构体指针

    所谓结构体指针就是指向结构体变量的指针,一个结构体变量的起始地址就是这个结构体变量的指针。如果把一个结构体变量的起始地址存放在一个指针变量中,那么,这个指针变量就指向该结构体变量。 目录 一、指向结构体变量的指针 1.1举例说明 二、指向结构体数组的指

    2024年02月06日
    浏览(31)
  • koa使用Sequelize:定义数据结构

    创建连接 测试连接 完整db定义类 常用DataTypes定义 添加model 为model添加初始 模型关联 一对一 文章 文章内容 关联关系定义 多对多 分类 文章分类关联表定义 关联关系定义(采用两个一对多的方式) 生成的关联表 如果采用多对多方式关联,始终都关联不上uid,可以用id关联。

    2024年02月09日
    浏览(24)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包