使用unique_ptr实现LeetCode 208前缀树(Trie)时的编译错误排查求助
unique_ptr Let's break down what's causing your error and how to fix it:
The Root Cause
Your code is trying to copy TrieNode instances (e.g., TrieNode currentNode = root;), which is invalid because TrieNode contains an unordered_map of unique_ptr<TrieNode>.
unique_ptr is non-copyable by design (its copy constructor is explicitly deleted), so any attempt to copy a structure containing unique_ptr will fail. When you assign currentNode = root, you're trying to copy the entire root node—including its unordered_map of unique_ptrs—which the compiler rejects.
The Solution: Use Pointers for Traversal
Instead of copying nodes, traverse the trie using pointers to existing nodes. This avoids any copy operations involving unique_ptr while still letting you navigate the trie structure.
Here's the corrected code:
class TrieNode{ public: std::unordered_map<char, std::unique_ptr<TrieNode>> childTrie; bool lastCharacter = false; }; class Trie { public: void insert(string word) { TrieNode* currentNode = &root; // Pointer to root, no copy for (auto c : word) { if (currentNode->childTrie.find(c) == currentNode->childTrie.end()) { currentNode->childTrie[c] = std::make_unique<TrieNode>(); } currentNode = currentNode->childTrie[c].get(); // Move pointer to child } currentNode->lastCharacter = true; } bool search(string word) { TrieNode* currentNode = &root; for (auto c : word) { if (currentNode->childTrie.find(c) == currentNode->childTrie.end()) { return false; } currentNode = currentNode->childTrie[c].get(); } return currentNode->lastCharacter; } bool startsWith(string prefix) { TrieNode* currentNode = &root; for (auto c : prefix) { if (currentNode->childTrie.find(c) == currentNode->childTrie.end()) { return false; } currentNode = currentNode->childTrie[c].get(); } return true; } TrieNode root; };
Key Changes:
- Replace copied nodes with pointers:
TrieNode* currentNode = &root;gives us a pointer to the root node instead of creating a copy. - Use pointer syntax: Access members with
currentNode->instead of.since we're working with pointers. - Traverse via raw pointers: Use
.get()onunique_ptrto get a raw pointer to the child node. This doesn't transfer ownership (theunique_ptrstill manages the child's memory)—it just lets us navigate to it.
This approach keeps your unique_ptr memory management intact while eliminating the invalid copy operations that caused the compilation error.
内容的提问来源于stack exchange,提问作者Marcus Raty

