用C泛型列表操作功能? [英] Generic list manipulation function in C?

查看:134
本文介绍了用C泛型列表操作功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是用C泛型列表操作函数?
(我看到这个的时候我正在经历一些材料。)

What is a generic list manipulation function in C? (I saw this when I was going through some materials.)

什么是这个功能,它可以接受任何一种元素的功能区别?

What is the difference between this function and a function which can accept elements of any kind?

他们是一样的... ...?我们如何可以单独实现他们,如果他们不一样呢?

Are they same...? How can we implement them individually if they are not same?

推荐答案

一个泛型列表很可能是单链表,也许假定在列表中的项目有这样的结构:

A generic list is likely to be singly-linked, and probably assumes that the items in the list have a structure like this:

typedef struct list_item list_item;

struct list_item
{
    list_item *next;
    ...data for node...
};

使用此布局,您可以编写函数来操作仅使用next指针列表。

Using this layout, you can write functions to manipulate lists using just the next pointers.

有时, ...节点的数据... '将是一个简单的无效* ';即,列表项将包含在列表中的指针到下一个节点(或NULL如果没有下一个节点),并指向数据

Sometimes, the '...data for node...' will be a simple 'void *'; that is, the list items will contain pointers to the next node in the list (or NULL if there is no next node) and pointers to the data.

typedef struct list list;

struct list
{
    list *next;
    void *data;
};

既然你可以施放任何指针无效* ,您可以在列表中的数据类型的任意组合 - 但你的code必须知道如何处理它们。

Since you can cast any pointer to 'void *', you can have any mix of data types in the list - but your code must know how to handle them.

您询问'A'泛型列表的功能,但也有可能是没有一个功能 - 确实,所有的设计,更不是一个简单的问题。有许多可能的集合的功能,可以使通用的列表的功能。一组由Lisp的启发,将包括:

You ask about 'a' generic list function, but there probably isn't a single one-function-does-all design, and certainly not a simple one. There are a number of possible sets of functions that could make generic list functions. One set, inspired by Lisp, would consist of:

void *car(list *lp);    // Return the data for the first item on the list
list *cdr(list *lp);    // Return the tail of the list
list *cons(list *lp1, list *lp2);   // Construct a list from lists lp1 and lp2

list *cond(list *lp, void *data);  // Append data item to list

您可能要提供给测试列表是否为空的能力,和其他几个项目。

You probably want to provide the ability to test whether the list is empty, and a few other items.

一个很好的论述,承认在C ++中,在柯尼的反刍在C ++中 。这些想法可以适应为C很容易 - 它不是可怕硬(虽然C中的存储管理比C ++更难)

One good exposition, admittedly in C++, is found in Koenig's "Ruminations on C++". The ideas can be adapted into C quite easily - it isn't dreadfully hard (though the storage management in C is harder than in C++).

这篇关于用C泛型列表操作功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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