如何使用从SYS / queue.h列表? [英] How to use list from sys/queue.h?

查看:329
本文介绍了如何使用从SYS / queue.h列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我实现了一个单向链表,像这样:

Currently, I have implemented a singly linked list, like so:

struct PeerNode {
     struct Peer* cargo;
     struct PeerNode* next;
};

...我有一个包含一对夫妇这些链接列表,像这样一个结构:

...and I have a struct that contains a couple of these linked lists, like so:

struct Torrent {
     ...
     struct PeerNode* peer_list;
     struct PeerNode* unchoked_peers;
     ...
}

我想通过使用提供的宏SYS / queue.h 替换此。据我了解,我可以像这样的东西取代我的code:

I would like to replace this by using the macros provided by sys/queue.h. I gather that I could replace my code with something like this:

struct Torrent {
     ...
     LIST_ENTRY(PeerNode, Peer) peer_list;
     struct PeerNode* unchoked_peers;
     ...
}

然后,看着男人队列,我相信我会做这样的事情初始化列表:

Then, from looking at man queue, I believe I would initialize the lists by doing something like this:

LIST_INIT(&peer_list);
LIST_INIT(unchoked_peers);

不过,我不明白怎么 LIST_ENTRY 因素纳入列表的使用。从页,它说:宏 LIST_ENTRY 声明的元素列表中的连接结构,但我真的不明白这意味着什么。

However, I don't understand how LIST_ENTRY factors into usage of the list. From the man page, it says: "The macro LIST_ENTRY declares a structure that connects the elements in the list," but I don't really understand what this means.

我为什么要声明一个结构,在列表中的元素进行连接?不应该每个节点通过指针连接到下一个节点,就像我最初的链表实现?我将如何与 SYS / queue.h 提供的实现取代我的链接列表?我怎么会插入一个元素到列表中?

Why would I want to declare a structure to connect the elements in the list? Shouldn't each node be connected to the next node via a pointer, like my initial linked list implementation? How would I replace my linked lists with the implementation provided by sys/queue.h? How would I insert an element into the list?

推荐答案

LIST_ENTRY创建领域投入你的结构适合于连接的元素,所以你不必与指针的具体关心自己。

LIST_ENTRY creates fields to put into your structure that are suitable for linking the elements, so you do not have to concern yourself with the specifics of those pointers.

struct foo {
    int a, b, c;
    /* This is instead of "struct foo *next" */
    LIST_ENTRY(foo) pointers;
};

要创建,然后你会使用LIST_HEAD()的列表:

To then create a list you'd use LIST_HEAD():

struct Torrent {
    LIST_HEAD(foo_list, foo) bar;
};

您可以用LIST_INIT()初始化列表标题:

You can initialise the list header using LIST_INIT():

struct Torrent t;
LIST_INIT(&t.bar);

您可以插入使用LIST_INSERT _ *()宏元素:

You can insert elements using the LIST_INSERT_*() macros:

struct foo *item = malloc(sizeof(struct foo));
LIST_INSERT_HEAD(&t.bar, item, pointers);

这是所有从man页面列表例如在 http://www.manpagez.com/man采取/ 3 /队列/

This was all taken from the list example in the man pages at http://www.manpagez.com/man/3/queue/

有关完整示例: http://www.ideone.com/T1EID

这篇关于如何使用从SYS / queue.h列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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