When one writes C++ code to manipulate LinkedLists, Trees, etc. one creates a tmp pointer that points to the start/root and changes that pointer as one traverses along.
What would be the equivalent way of doing that in smart pointers?
Here, I wrote a Trie code using std::unique_ptr
to understand how to pass pointers around. To make the program work, I had to dive inside the smart pointer and access the underlying raw pointer. Is this the right way of doing things? Or is it in fact possible to pass the unique_ptr
around? I believe std::move
will not be a good idea here since it will a destructive operation.
My code is as follows. Special call out to .get()
function to get the raw pointer.
#include <iostream>
#include <memory>
#include <map>
class TrieNode
{
public:
bool isLeaf{ false };
std::map<char, std::unique_ptr<TrieNode>> children;
};
class Trie
{
std::unique_ptr<TrieNode> root{nullptr};
public:
Trie()
{
root.reset(new TrieNode());
}
void insert(const std::string& word)
{
auto node = root.get();
for (auto ch : word)
{
if (node->children.find(ch) == node->children.end())
{
node->children[ch] = std::make_unique<TrieNode>();
}
node = node->children[ch].get();
}
node->isLeaf = true;
}
bool search(const std::string& word) const
{
auto node = root.get();
for (auto ch : word)
{
if (node->children.find(ch) == node->children.end())
{
return false;
}
node = node->children[ch].get();
}
return (node && node->isLeaf);
}
};
int main()
{
Trie trie;
trie.insert("application");
std::cout << "does apple there in the trie? " << (trie.startsWith("app") ? "yes" : "no") << std::endl;
std::cout << "is application there in the trie? " << (trie.search("apple") ? "yes" : "no") << std::endl;
return 0;
}
unique_ptr
. You need ashared_ptr
. \$\endgroup\$std::string_view
objects, iterators or indeed C++ references. \$\endgroup\$