我如何在c ++中创建一个列表? [英] How could i create a list in c++?

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

问题描述

如何在C ++中创建列表?我需要它来创建一个链表。我怎么会这样做?

How can I create a list in C++? I need it to create a linked list. How would I go about doing that? Are there good tutorials or examples I could follow?

推荐答案

我认为你知道C ++已经有一个链接列表类,你想实现自己的,因为你想学习如何做到。

I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.

首先,请阅读 http:// stackoverflow。 com / questions / 392397 / arrays-whats-the-point ,其中包含基本数据结构的良好答案。然后考虑如何在C ++中对它们建模:

First, read http://stackoverflow.com/questions/392397/arrays-whats-the-point , which contains a good answer of basic data-structures. Then think about how to model them in C++:

struct Node {
    int data;
    Node * next;
};

基本上这就是实现列表所需要的! (很简单)。但它没有抽象,你必须链接每个手的项目:

Basically that's all you need to implement a list! (a very simple one). Yet it has no abstractions, you have to link the items per hand:

Node a={1}, b={20, &a}, c={35, &b} d={42, &c};

现在,您已经有一个链接的节点列表,所有节点都在堆栈上分配:

Now, you have have a linked list of nodes, all allocated on the stack:

d -> c -> b -> a
42   35   20   1

下一步是写一个包装类 List 指向起始节点,并允许根据需要添加节点,跟踪列表的头部(以下是非常简化的):

Next step is to write a wrapper class List that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified):

class List {
    struct Node {
        int data;
        Node * next;
    };

    Node * head;

public:
    List() {
        head = NULL;
    }

    ~List() {
        while(head != NULL) {
            Node * n = head->next;
            delete head;
            head = n;
        }
    }

    void add(int value) {
        Node * n = new Node;
        n->data = value;
        n->next = head;
        head = n;
    }

    // ...
};

下一步是使List成为模板,以便您可以填充其他值)。

Next step is to make the List a template, so that you can stuff other values (not only integers).

如果您熟悉智能指针,则可以替换与智能指针一起使用的原始指针。通常我发现人们推荐智能指针。但在我看来,你应该首先了解为什么你需要智能指针,然后使用它们。但这需要你首先了解原始指针。否则,你使用一些魔术工具,不知道为什么你需要它。

If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.

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

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