首页 > 解决方案 > 在 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 就在这里

标签: c++templating

解决方案


有几点需要注意:

现在来解决代码中的一些问题。我不确定是否template <class t, class t>有效,但在这种情况下充其量是没用的。解决您的问题:是的,这两个class ts 相互干扰,但您不需要两个不同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++ 的基础知识。在你能走路之前你不能跑步。


推荐阅读