c++ - BST 的 C++ 回调函数和函数指针问题

标签 c++ binary-search-tree pointer-to-member

我必须创建一个二叉搜索树,它是模板化的,可以处理任何数据类型,包括像对象这样的抽象数据类型。由于不知道对象可能具有什么类型的数据以及将要比较哪些数据,因此客户端必须创建一个比较函数以及一个打印函数(因为也不确定必须打印哪些数据)。

我已经编辑了一些我被引导到的 C 代码并尝试模板化,但我不知道如何配置客户端显示功能。我怀疑必须传入类 BinarySearchTree 的变量“tree_node”,但我不确定如何执行此操作。

对于这个程序,我正在创建一个整数二叉搜索树并从文件中读取数据。对代码或问题的任何帮助将不胜感激:)

main.cpp

#include "BinarySearchTreeTemplated.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

/*Comparison function*/
int cmp_fn(void *data1, void *data2)
{
    if (*((int*)data1) > *((int*)data2))
        return 1;
    else if (*((int*)data1) < *((int*)data2))
        return -1;
    else
        return 0;
}

static void displayNode()  //<--------NEED HELP HERE
{
    if (node)
        cout << " " << *((int)node->data)
}

int main()
{
    ifstream infile("rinput.txt");
    BinarySearchTree<int> tree;

    while (true) {
        int tmp1;
        infile >> tmp1;
        if (infile.eof()) break;
        tree.insertRoot(tmp1);
    }
        return 0;
}

BinarySearchTree.h(有点太大,无法在此处格式化)

http://pastebin.com/4kSVrPhm

最佳答案

我觉得服务器端应该提供比较和打印功能。这也可以作为模板完成。

template <class T>
int cmp_fct( const T& rhs, const T& lhs ) {
    if( rhs < lhs) return -1;
    else if (rhs > lhs) return 1;
    return 0;
}

显示节点的过程相同。

现在客户端必须提供一些运算符:

struct TestObject {
    int i;

    friend bool operator<( const TestObject& rhs, const TestObject& lhs ) {
        return rhs.i < lhs.i;
    }

    friend bool operator>( const TestObject& rhs, const TestObject& lhs ) {
        return lhs < rhs;
    }

    // and stream operators 
    friend std::ostream& operator<<( std::ostream& output, const TestObject & ob)
    {
        output << ob.i;
        return output;
    }
};

此外,我会考虑为您的 BinarySearchTree 使用 c++ 方法,即使用 smart pointers而不是原始指针。

您的 BinarySearchTree 创建对象但从不删除它们。

避免使用空指针,使用接口(interface)(例如 INode),客户端必须从接口(interface)派生......

使用构造函数初始化列表,否则,对象由默认构造函数创建,然后在构造函数中重新分配。

关于c++ - BST 的 C++ 回调函数和函数指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23907629/

相关文章:

c++ - 如何禁止其他开发人员在 C++ 中#include 第三方 header

c++ - #include <fstream> visual c++ 2010 无法正常工作

c++ - 删除有两个 child 的目标

c++ - 将函数传递给方法原型(prototype)

c++ - C++ 成员函数表

c++ - 在浏览器中运行 c++

algorithm - 解释为什么插入(以及不同的情况)不会改变红黑树的黑色高度

java - 如何在 2-3 树 java 中找到正确的子节点进行搜索

c++ - std::invoke 和指向类成员的复杂函数指针

c++ - 如果我将 Visual Studio 版本 2008 更改为 2010,程序将无法运行