列出C++中的实现
List implementation in C++
这次我没有问题,但我只是在寻找List实现,只是一个包含Node(int,nextNode)等节点的简单列表。我过去做过很多次,但我的 c++ 有点生疏。你能和我分享一下吗?我正在github上查找我的档案,但我没有找到antyhing。
编辑:
*我决定做我的,我不明白为什么使用删除后我仍然可以得到cout<getWrt()><*>
#include <cstdio>
#include <cmath>
#include<iostream>
using namespace std;
class Node{
public:
Node(Node* next, int wrt){
this->next = next;
this->wrt = wrt;
}
Node(const Node& obiekt){
this->wrt = obiekt.wrt;
this->next = obiekt.next;
}
~Node(){}
void show(){
cout<<this->wrt<<endl;
}
int getWrt(){
return this->wrt;
}
Node* getNext(){
return this->next;
}
private:
Node* next;
int wrt;
};
int main()
{
Node* n = new Node(NULL, 2);
n->show();
Node* n2 = new Node(*n);
n2->show();
delete n;
n->show();
n2->show();
return 0;
}
基本的列表实现通常被称为单链表(或在函数式语言中称为 cons-list)。
功能定义直接切入列表的结构:
List := Empty | Cons T List
当然,这在 C 或 C++ 中并不真正有效,因此我们需要将结构一分为二:
- 该列表实现为节点链
- List 类隐藏此实现详细信息
下面是一些简单的代码:
template <typename T>
struct Node {
Node(T t): element(t) {}
T element;
std::unique_ptr<Node> next;
};
template <typename T>
class List {
typedef Node<T> N;
public:
List() {}
bool empty() const { return head == nullptr; }
T& front() { assert(!this->empty()); return head->elem; }
T const& front() const { { assert(!this->empty()); return head->elem; }
void pop() { assert(!this->empty()); swap(head, head->next); }
void push(T t) {
std::unique_ptr<N> n{ new Node {t} };
n->next = std::move(head);
head = std::move(n);
}
private:
std::unique_ptr<N> head;
};
如您所见,此列表只是作为堆栈实现的,没有迭代等......尽管如此,这仍然是一个良好的开端:)
正如 aix 所说,你最好的选择是选择......
- std::list,这是一个双向链表,这意味着它用向后遍历速度换取内存使用或
- 不太广泛实现的std::slist(在C++11中称为forward_list),它是单链接的,只能以一种方式遍历。
当然,cplusplus.com 两者都有参考信息。
作为 STL 的一部分,这两个列表实现都经过了广泛的测试、调优和调试。两者都支持标准的 STL 算法。几乎没有理由不使用它们。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的