BST模板类中使用的矢量模板类

问题描述 投票:0回答:2

如何处理这样的任务。我实现了BST模板类,它能够对像intfloat等简单类型进行操作。现在我想实现另一个模板类Vector并在BST模板类中为这种类型添加不同的功能,因为在Vector类型的情况下每个比较比较Vector长度不仅仅是值(在这种情况下是两个值)。

bst.h

#ifndef BSTTREE_BST_H
#define BSTTREE_BST_H

template <class T> class bst {
   struct node {
       T d;
       node *l, *r;
    };
    node* root;
public:
    bst();
    ~bst();
    void freeMemory(node* bstNode);
    void insert(T x); 
    void show(); 
    void show(node* bstNode);
    int count(node* bstNode);
    node* search(T x);
    node* search(node* bstNode, T x);
    bool rmv(T x); 
};

#include "bst.cpp"
#endif //BSTTREE_BST_H

bst.cpp

#ifndef BSTTREE_BST_CPP
#define BSTTREE_BST_CPP

#include "bst.h"
#include <iostream>

template <class T>
bst<T>::bst() {}

template <class T>
bst<T>::~bst() {}

template <class T>
void bst<T>::freeMemory(bst::node *node) {}

template <class T>
void bst<T>::insert(T x){}

template <class T>
void bst<T>::show() {}

template <class T>
void bst<T>::show(node* root) {}

template <class T>
int bst<T>::count(node* root) {}

template <class T>
typename bst<T>::node* bst<T>::search(T x) {}

template <class T>
typename bst<T>::node* bst<T>::search(node* root, T x) {}

template <class T>
node* bst<T>::rmv(int value, node *parent) {}

#endif //BSTTREE_BST_CPP

我没有实现内部方法的方法,因为它工作得很好而且不是任务。我知道这些代码中的一些内容是错误的,但我必须遵循一些规则,在我看来并不是很聪明,但这不是重点。

我想在.h / .cpp文件中创建另一个模板类vector,并在bst.cpp中包含Vector类的标题,并为Vector类模板写入其他功能。这是个好主意吗?或者有更好的方法(如果可能的话,不会更改我的代码)。怎么做?

c++ templates
2个回答
2
投票

C ++支持operator overloading,这意味着如果你坚持使用特定的比较运算符,例如*(root->l) < *(root->r),它将与intfloat等基本类型一起正常工作。

同时您可以定义自定义

bool Vector::operator<(const Vector& other) const { return this->length() < other.length(); }

这样,在比较Vector实例时,BST模板类将正确调用指定的重载方法。


0
投票

您可以尝试创建一个重载函数来比较这两个值,并在该函数中添加第三个参数,而不是为特定的vector类添加函数,该函数可以是一个函数指针,您可以在vector类中定义它。

示例::

void func1(T v1, T v2, (bool) (*compare) (T, T));

T是模板类型)

你可以创建这个compare函数,它不仅可以比较长度,还可以根据情况比较其他一些属性,并且在func1中使用compare返回的结果。

更多关于函数指针How do function pointers in C work?

© www.soinside.com 2019 - 2024. All rights reserved.