I'm learning C++ and whilst trying to write in modern C++, I've made an attempt to rewrite a trie implementation written in C found here: http://www.geeksforgeeks.org/trie-insert-and-search/
It uses arrays to hold the branches in each node and because it's C it was done using malloc() and no freeing of memory was done in the example.
Is this an efficient approach of representing a trie in C++11? what other ways can I store children in trie nodes?
#include <iostream>
#include <map>
#include <algorithm>
#include <memory>
class Trie {
struct Node;
typedef std::unique_ptr<Node> spNode;
struct Node {
std::map<char, spNode> children;
bool isLeaf;
Node() : isLeaf{false} {}
};
spNode root;
public:
Trie();
void insert(const std::string& str);
bool search(const std::string& str);
};
Trie::Trie():root{nullptr}{}
void Trie::insert(const std::string& str) {
if (root == nullptr) {
std::unique_ptr<Node> node(new Node());
root = std::move(node);
}
Node *temp = root.get();
for (const char& c : str) {
if (temp->children.find(c) == temp->children.end()) {//if char not in map
std::unique_ptr<Node> node(new Node());
temp->children[c] = std::move(node);
}
temp = temp->children[c].get();
}
temp->isLeaf = true;
}
bool Trie::search(const std::string &str) {
if (root == nullptr) return false;
Node *temp = root.get();
for (const char& c : str) {
if (temp->children.find(c) == temp->children.end())
return false;
temp = temp->children[c].get();
}
return (temp->isLeaf);
}
int main (void) {
std::string words[] = { "Hello", "hi", "hey", "howdy", "ho"};
Trie test;
for (const auto& str : words) {
test.insert(str);
}
if (test.search("Hello"))
std::cout << " 'Hello' is found in the trie\n";
else
std::cout <<" 'Hello' is not found in the trie\n";
if (test.search("yo"))
std::cout << " 'yo' is found in the trie\n";
else
std::cout << " 'yo' is not found in the trie\n";
}
hash-map
here.std::map
has the same characteristics as a tree.std::unordered_map
is closer to ahash-map
but I believe has a much larger space requirements. \$\endgroup\$