c++ - 在 C++ 中模板化列表
问题描述
我正在编写一个需要我不久前编写的 SkipList 的程序,但现在我需要将其模板化,因为它需要使用我创建的自定义类。我遇到的问题是在 List 类中创建节点。我template <class t>
在所有方法上都使用,但我认为由于节点和 SkipList 类都使用template <class t>
,相同class t
的 s 会相互干扰或其他东西。
在我的 SkipList.h 中,我有方法说
Node <t>* createnode<t>(t,int);
在 SkipList.cpp 中,该方法说
template <class t>
Node<t>* SkipList<t>::createnode(t value, int level) {
Node<t> *n = new Node<t>(value, level);
return n;
}
这在 .h 文件中给了我一个错误Template specialization requires 'template<>'
,当我添加它时,它会替换要说的代码
template<> Node<t>* createnode<t>(t,int);
但是后来我的 .cpp 文件说没有函数定义了。
有谁知道我哪里出错或我错过了什么?非常感谢您的帮助。如果有人需要澄清,我的 GitHub 就在这里
解决方案
有几点需要注意:
- 您不能在
.cpp
文件中使用 headers定义模板。 using namespace std;
可以并且将导致令人讨厌的事情,尤其是当包含在这样的标题中时。- 你不应该包括
bits/stdc++.h
.
现在来解决代码中的一些问题。我不确定是否template <class t, class t>
有效,但在这种情况下充其量是没用的。解决您的问题:是的,这两个class t
s 相互干扰,但您不需要两个不同t
的 s。你不能创建一个Node<t>
不t
匹配的类型List
可以吗?现在,即使您有需要的情况,您也可以使用template <class T1, class T2>
.
现在固定的实现看起来像这样:
template <class T>
class SkipList {
int MAX_LEVEL;
float p;
Node<t>* header;
int level;
public:
SkipList<T>(int,float) { /* Include definition here */}
int randomlevel() { /* Include definition here */}
void insert(T) { /* Include definition here */}
void remove(T) { /* Include definition here */}
bool find(T) { /* Include definition here */}
void print() { /* Include definition here */}
Node<T>* createnode(T, int) { /* Include definition here */}
};
同样Node
也应该修复(包括构造函数的定义)。
您在帖子中提到的另一件事是模板专业化。你可以在这里阅读。
您的Node
/SkipList
类之间的某处也存在内存泄漏。考虑转向智能指针。
最后,我强烈建议您在继续之前先了解 C++ 的基础知识。在你能走路之前你不能跑步。
推荐阅读
- javascript - 自定义 vuetify 选择/组合框/自动完成弹出框
- python - 开放轮廓线图的分割
- reactjs - 当 Accordion 处于展开状态时,如何将样式应用于 MUI Accordion 中的 expandIcon?
- python - 带有数据框的条件语句/If 语句
- elasticsearch - Elasticsearch,仅在唯一时索引新文档(两个字段构成唯一索引)
- python - 为什么 Tkinter 窗口打开这么慢?
- android - 为什么 android NFC 可以读取一些非接触式 emv 信用卡而不是其他的?
- material-ui - Material UI 对话框 - 为什么在使用 NVDA 激活的键盘重新打开对话框时焦点会移动?
- django - 无法在 Django 中加载静态文件:
- javascript - JS/JQuery - 让展开/折叠工作出现问题