【发布时间】:2023-03-14 02:00:01
【问题描述】:
我有一个实验室任务,我在过去几周一直在努力,我陷入困境并且迫切需要帮助,因为这将是最终项目的 50%。 任务是在 C++ 中创建一个二叉搜索树。我们必须将独立宣言中的文字读入二叉搜索树。我的搜索和插入方法“正常工作”,这意味着它们不会引发任何错误。我遇到的问题是显示 BST 以确定一切是否正常。 display 方法应该被重载的操作符 >> 调用来显示树。 我不断收到的错误是:
“错误 C3867: 'BST::display': 缺少函数调用 参数列表;使用 '&BST::display' 创建指向 会员”
另一个是
"error C2679: binary '
上次我重建程序时,它显示“ItelliSense:指向绑定函数的指针只能用于调用该函数。”
#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
template <typename T>
class BST{
private:
struct node {
T data;
struct node* left;
struct node* right;
};
node* root;
public:
BST()
{
root = NULL;
}
bool isEmpty() const { return root == NULL; }
~BST();
template <typename T>
void insert(T d)
{
node* t = new node;
node* parent;
t->data = d;
t->left = NULL;
t->right = NULL;
parent = NULL;
if (isEmpty()) root = t;
else {
node* current;
current = root;
while (current)
{
parent = current;
if (t->data > current->data) current = current->right;
else current = current->left;
}
if (t->data < parent->data)
parent->left = t;
else
parent->right = t;
}
}
template<typename T>
bool search(T d)
{
if (root == NULL)
return false;
else if (d == root->item) {
return true;
}
else if (d < root->item) {
return search(root->left, d);
}
else {
return search(root->right, d);
}
}
template<typename T>
void display(node *p, std::ostream& os)
{
if (p != NULL)
{
if (p->left) display(p->left);
os << " " << p->data << " ";
if (p->right) display(p->right);
}
}
template<typename T> friend std::ostream& operator<<(std::ostream& os, const BST<T>& obj)
{
obj.display(os, obj.root);
}
};
int main( )
{
BST<string> s;
ifstream inFile;
string word, tmp;
string filename = "Independence.txt";
ifstream fstr(filename.c_str());
while (inFile >> word) {
s.insert(word);
}
inFile.close();
cout << s << std::endl;
cout << "Search for: ";
cin.ignore(1);
cin >> tmp;
s.search(tmp);
return 0;
};
【问题讨论】:
标签: c++ templates binary-search-tree