Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/130.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用map实现Trie_C++_Algorithm_Data Structures - Fatal编程技术网

C++ 使用map实现Trie

C++ 使用map实现Trie,c++,algorithm,data-structures,C++,Algorithm,Data Structures,实现Trie数据结构的简单方法是使用std::map。如果我使用它,会发生什么错误。我需要序列化和反序列化Trie。因此,节点中的每个映射都是AVL树。也许我会有开销?但在地图中,若我使用列表,我可以更快地搜索 template < typename T > struct NodeTrie{ std::map<char,*NodeTrie>` bool isWord; T & val; }; 模板 结构节点{ 标准::地图` 布尔语; T

实现Trie数据结构的简单方法是使用
std::map
。如果我使用它,会发生什么错误。我需要序列化和反序列化Trie。因此,节点中的每个映射都是AVL树。也许我会有开销?但在地图中,若我使用列表,我可以更快地搜索

template < typename T >
struct NodeTrie{
    std::map<char,*NodeTrie>`
    bool isWord;
    T & val;
};
模板
结构节点{
标准::地图`
布尔语;
T&val;
};

我喜欢你的想法。尝试是重要的数据结构,我对将地图作为高效容器有着愉快的体验

请注意:如果您的编译器支持它,您可以通过为每个节点单独分配内存来避免浪费内存

template< typename T >
struct NodeTrie {
    NodeTrie(const T& val = T(), bool isWord = bool() ) : val(val), isWord(isWord) {}

    std::map<char, NodeTrie> span;
    T val;
    bool isWord;
};
模板
结构节点{
NodeTrie(const T&val=T(),bool-isWord=bool()):val(val),isWord(isWord){
地图跨度;
T值;
布尔语;
};
要这样使用:

int main() {
    typedef NodeTrie<int> iTree;
    iTree t(0);
    t.span['a'] = iTree(3);
    ...
}
intmain(){
typedef NodeTrie iTree;
itreet(0);
t、 span['a']=iTree(3);
...
}

此外,我还将
val
成员更改为可复制的可构造对象:在这里使用引用对我来说似乎是错误的设计…

仅供参考,GNU libc++的基于策略的数据结构库中已经有一个trie模板。您可以像这样使用它:

#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/trie_policy.hpp>
using namespace std;
using namespace pb_ds;

trie <string, int> myTrie;
#包括
#包括
使用名称空间std;
使用名称空间pb\U ds;
崔米崔;

有关使用此类的一些示例,您可以参考。

是否有类似于hashmap的数据结构?你可以用它来减少开销。或者,如果没有,那么考虑将一个字符映射到更易于管理的对象。对于词汇搜索,我需要确切的Trie。那么,您的问题“在实现Trie节点时,我是否应该使用
std::map
”(看起来是这样,但是…)是什么让您认为使用map搜索会更快?对于小数据集,大的Oh符号很容易产生误导(例如255个或更少的键)。@Ubitso这700000个键是trie作为一个整体处理的。在每个
NodeTrie
的映射中,您只有
char
键,即最多255个键,很可能更少。