如何在C或C ++中创建异构链接列表 [英] how to create a heterogeneous link list in c or c++

查看:115
本文介绍了如何在C或C ++中创建异构链接列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以容纳浮点数,整数,字符等数据和算法的链接列表应该很好并且不是很复杂

A link list that can hold float,integer,character,etc data and algorithm should be well and not very complex

我想创建一个带有空指针的结构它将指向后续节点。但是问题是我不能使用具有结构的模板。

I thought of creating a structure with void pointer that will point to subsequent nodes. but problem is that i cannot use templates with structure.

降到c,我必须测试用户输入的每个字符以测试它是integer,float还是character还是不可以。那么我们可以进一步进行

coming down to c, i have to test each character entered by user to test whether it is integer , float or character or not.then we can proceed further

请提出一种有效的算法/代码

please suggest an efficient algorithm/code

推荐答案

如果您想自己执行此操作,则基本上需要创建一个数组或元素的链接列表,以对数据和数据类型进行编码。您可以使用包含类型指示器和要处理的各种类型的并集的结构,并创建该结构的数组或链接列表:

If you want to do this yourself you'll basically want to create an array or linked list of elements that encode both the data and the type of data. You could use a struct that includes a type indicator and a union of the various types that you want to handle, and the create an array or linked list of that struct:

typedef struct {
    int type_indicator;
    union {
        float f;
        int i;
        double d;
        void *p;
        char c;
    }
} generic_item;

generic_item generic_array[10];

我将留给您为类型指示符提供适当的枚举并添加算法的函数指针。如果要使用链接列表而不是数组,显然还需要添加 generic_item * next 指针。

I'll leave it to you to come up with an appropriate enumeration for the type indicator and to add a function pointer for your algorithm. If you want a linked list instead of an array, you'll obviously also need to add a generic_item *next pointer.

我没有研究其他答案链接到的boost选项,但是在尝试推出自己的解决方案之前,我可能会先看一下。

I haven't looked into the boost options that other answers link to, but I'd probably look there first before trying to roll my own solution.

这篇关于如何在C或C ++中创建异构链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆