用于BST的C ++中的回调函数和函数指针问题

时间:2014-05-28 09:22:56

标签: c++ binary-search-tree member-function-pointers

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

我已经编辑了一些C代码,我被引导到并尝试模板,但我无法弄清楚如何配置客户端显示功能。我怀疑变量' tree_node'必须传入BinarySearchTree类,但我不知道如何做到这一点。

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

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

1 个答案:

答案 0 :(得分:1)

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

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;
}

displayNode的相同过程。

现在客户必须提供一些运营商:

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会创建对象但不会删除它们。

避免使用void-pointers,使用Interfaces(例如INode),而不是客户端必须从接口派生...

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