正在尝试在avl树中实现find
Attempting to implement find in avl tree
我正在使用以下代码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。
相关文章:
- 如果没有malloc,链表实现将失败
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- OpenMP卸载说'fatal error: could not find accel/nvptx-none/mkoffload'
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 在libc++和libstdc++之间的std::map上使用std::find时的实现差异
- 如何在C++中从头文件中实现:find()和::count()
- 正在尝试在avl树中实现find
- 比较STL堆中std::shared_ptr和std::find的值.(试图实现A*)
- 自己的 std::string::find (暴力搜索)实现
- 在 LLVM libc++ 中找到的 string::find 中实现的算法(及其复杂性)是什么?
- 为什么std::find是这样实现的
- 在哪里可以找到std::string::find()的完整实现