简体   繁体   中英

Trie implementation with using map

Easy way for realize Trie data structure are use std::map<char,*NodeTrie> . What can happens wrong if I use that. I need serialize and deserialize Trie. So each map in the node is AVL- tree. Maybe I'll have overhead? But in map I can search faster, that if I use list.

template < typename T >
struct NodeTrie{
    std::map<char,*NodeTrie>`
    bool isWord;
    T & val;
};

I like your idea. Tries are important data structures, and I had pleasant experience with map<>s as efficient containers.

Just some remarks: if your compiler support it, you could avoid wasting memory with a separate allocation for each node.

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;
};

To be used this way:

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

Also I changed the val member to be a copy constructible object: using a reference here seems wrong design to me...

Just FYI, GNU libc++ has a trie template already in its policy based data structure library. You can use it like:

#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;

For some examples in using this class you can refer to this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM