正在尝试在avl树中实现find

Attempting to implement find in avl tree

本文关键字:实现 find avl      更新时间:2023-10-16

我正在使用以下代码https://rosettacode.org/wiki/AVL_tree#C.2B.2B作为AVL树的基础。默认情况下,该示例使用整数,但是我需要存储字符串。因此,我修改了代码进行调试,主要是将根公开并尝试打印值。

22 /* AVL tree */
 23 template <class T>
 24 class AVLtree {
 25         public:
 26                 AVLtree(void);
 27                 ~AVLtree(void);
 28                 bool insert(T key);
 29                 void deleteKey(const T key);
 30                 void printBalance();
 31                 AVLnode<T> *root;
 32 
 33         private:
 34 
 35                 AVLnode<T>* rotateLeft          ( AVLnode<T> *a );
 36                 AVLnode<T>* rotateRight         ( AVLnode<T> *a );
 37                 AVLnode<T>* rotateLeftThenRight ( AVLnode<T> *n );
 38                 AVLnode<T>* rotateRightThenLeft ( AVLnode<T> *n );
 39                 void rebalance                  ( AVLnode<T> *n );
 40                 int height                      ( AVLnode<T> *n );
 41                 void setBalance                 ( AVLnode<T> *n );
 42                 void printBalance               ( AVLnode<T> *n );
 43                 void clearNode                  ( AVLnode<T> *n );
 44 };
..................................
247 int main(void)
248 {
249         AVLtree<std::string> t;
250 
251         std::cout << "Inserting integer values 1 to 10" << std::endl;
252         for (int i = 1; i <= 10; ++i)
253                 t.insert(i+" ");
254 
255         std::cout << "Printing balance: ";
256         t.printBalance();
257         std::cout << t.root->key + "n";
258         std::cout << t.root->left->key + "n";
259         std::cout << t.root->left->right->key + "n";
260         std::cout << t.root->key;
261 
262 }

但是问题是打印出来的结果是

Inserting integer values 1 to 10
Printing balance: 1 0 -1 0 0 1 0 0 1 0 
ing balance: 
Printing balance: 
g balance: 
ing balance: 

我不知道为什么。

我认为您正在将垃圾字符串插入到以下行的数据结构中:

for (int i = 1; i <= 10; ++i)
    t.insert(i+" ");

" "的类型是const char *,当您向它添加一个整数时,您会得到另一个从原始指针偏移的const char *。因为字符串" "恰好存储在程序中的字符串"Printing balance:"之前,所以在执行该代码时,您最终生成了指向"Printing balance:"字符串内部各个位置的指针。

要在C++中正确地将数字转换为字符串,可以使用std::To_string。