c++ - 红黑树模板

标签 c++ templates data-structures binary-search-tree red-black-tree

<分区>

我在实现使用模板的红黑树时遇到问题。我已经阅读并理解了目的,但不知道如何将它实现到头文件和 .cpp 文件中。我在一些论坛上读到它们必须与模板在同一个文件中,而其他人则说它们可以分开但在 .hpp 文件中。

头文件

enum nodeColor { RED, BLACK };

template <class myType>
struct nodeType
{

    myType  keyValue;
    nodeColor color;
    nodeType<myType> *left;
    nodeType<myType> *right;
    nodeType<myType> *parent;

};

template<class myType> 
class redBlackTree
{

public:
    redBlackTree() {}
    ~redBlackTree() {}
    void destroyTree();
    unsigned int countNodes() const;
    unsigned int height() const;
    void printTree() const;
    void insert(myType);
    bool search(myType);

private:
    bool search(myType, nodeType<myType> *);
    void destroyTree(nodeType<myType> *);
    unsigned int countNodes(nodeType<myType> *) const;
    unsigned int height(nodeType<myType> *) const;
    void printTree(nodeType<myType> *) const;
    void rightRotate(nodeType<myType> *);
    void leftRotate(nodeType<myType> *);

};

.cpp文件

#include "redBlackTree.h"
using namespace std;

redBlackTree::redBlackTree()
{
}   
redBlackTree::~redBlackTree()
{
}
void redBlackTree::destroyTree()
{
}
unsigned int redBlackTree::countNodes() const
{
}
unsigned int redBlackTree::height() const
{
}
void redBlackTree::printTree() const
{
}
void redBlackTree::insert(myType)
{
}
bool redBlackTree<myType>::search(myType)
{
}

bool redBlackTree::search(myType, nodeType<myType> *)
{
}
void redBlackTree::destroyTree(nodeType<myType> *)
{
}
unsigned int redBlackTree::countNodes(nodeType<myType> *) const
{
}
unsigned int redBlackTree::height(nodeType<myType> *) const
{
}
void redBlackTree::printTree(nodeType<myType> *) const
{
}
void redBlackTree::rightRotate(nodeType<myType> *)
{
}
void redBlackTree::leftRotate(nodeType<myType> *)
{
}

我也知道我没有包含参数。我主要问的是如何解决这个问题,以便我可以开始编写代码。

最佳答案

  1. 有多种方法可以在 .cpp 文件中实现类模板,但最常见的方法是在 .hpp(或 .h)文件中实现它们。参见 Why can templates only be implemented in the header file? .

  2. 更重要的是,您不得使用:

    redBlackTree::redBlackTree()
    {
    } 
    

    实现类模板成员函数。该语法只能用于类。您需要使用:

    template <typename myType>
    redBlackTree<myType>::redBlackTree()
    {
    } 
    

    并对所有其他功能进行更改。

关于c++ - 红黑树模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48916406/

相关文章:

c++ - 在不连续的 C++ 容器中,结束迭代器指向哪里?

具有相同名称的 C++ 虚拟覆盖函数

c++ - 在 C++ 的子类中强制执行静态方法重载

c++ - C++ 中用于不可变数组的模板函数

c - C中有向图中的DFS遍历

c++ - 从跳过列表中删除节点

c# - 在非托管 C++ DLL 和托管 C# UI 之间发送信息

c++ - glGenBuffers - 释放内存?

c++ - Enable_if 作为模板参数

mysql - 关系数据库结构 - 最佳实践?