【发布时间】:2019-12-30 21:05:36
【问题描述】:
我想使用 AVL 树结构作为字典下的基础。 我的班级:
template <typename keyType, typename dataType>
class AVLTree
{
class Node
{
public:
keyType key;
dataType data;
short int balanceFactor;
Node * left;
Node * right;
Node(const keyType & newKey, const dataType & newData) : key(newKey), data(newData), balanceFactor(0), left(NULL), right(NULL) {};
};
Node * Root;
***methods
void insert(AVLTree<keyType, dataType>::Node* & subtreeRoot, const keyType & newKey, const dataType & newData); //insert new element
void clear(AVLTree<keyType, dataType>::Node* & subtreeRoot); //clear whole tree
void graph(AVLTree<keyType, dataType>::Node* const & subtreeRoot, int indent) const; //print tree
void printDes(AVLTree<keyType, dataType>::Node* const & subtreeRoot) const; //print in descending order
void printAsc(AVLTree<keyType, dataType>::Node* const & subtreeRoot) const; //print in ascending order
...
public:
void search(const keyType & findKey) const;
...};
假设我得到一个句子:
我喜欢绿草和绿树。
当我去掉标点符号 ('.') 并降低我得到的所有单词时:
我喜欢绿草和绿树
我想把每个单词都放在AVL树的结构中,并打印为升序列表:
和- 1
草-1
绿色- 2
i -1
喜欢- 1
树木- 1
其中第二个“参数”是出现次数,即在 green 的情况下为 2。
我已经将它作为单链表的映射,但现在我想实现 AVL 树,我想知道下一步应该做什么。我打算用几种方法制作一个外部类 COUNTER,包括这个。我的想法:
遍历句子;如果单词 (key) 不存在(search 方法返回通知 - 应该变成布尔值?),添加它(insert 方法) 到树上。
如果它已经存在,增加第二个参数(在这种情况下,data)--- 如何? 如果没有,请将其添加到 data=1 的树中。
那么,最后一个问题是:我的想法正确吗?如果是这样,那么如何增加模板的第二个参数呢?迭代器是解决这个问题的方法吗?
编辑: 这是我使用单链表的实现,但没有使用 INFO:
template <typename key>
class counter {
sequence<key> list;
std::map<string, int> map;
public:
void add_word(key new_word) {
list.insertEnd(new_word);
auto iterator = map.find(new_word);
if (iterator != map.end()) {
iterator->second++;
} else {
map.insert({new_word, 1});
}
}
我想知道它可能会起作用:
template <typename key, typename info>
class counter {
AVLTree<key, info> dict;
std::map<string, int> map;
public:
void add_word(key new_word) {
dict.insert(new_word,1);
auto iterator = map.find(new_word);
if (iterator != map.end()) {
iterator->second++;
} else {
map.insert({new_word, 1});
}
}
...}
但我想它不会那样工作
【问题讨论】:
-
如果你能让你的AVL树类有和
std::map一样的接口就好了。
标签: c++ dictionary avl-tree