If we declare trie,
struct trie{
int count;
trie* next[26];
};
We use like that, but this approach takes much memory every time we put words, so new trie established. If we make one new trie, we must make 26 spaces due to that array.
Why we don't use unordered_map for "next", so we make space as needed every time we put the words in trie?
So i use
struct trie{
int count;
unordered_map <char,trie*> next;
};
and it works.
Is there any disadvantage for unordered_map than arr[26]?
If we declare trie,
struct trie{
int count;
trie* next[26];
};
We use like that, but this approach takes much memory every time we put words, so new trie established. If we make one new trie, we must make 26 spaces due to that array.
Why we don't use unordered_map for "next", so we make space as needed every time we put the words in trie?
So i use
struct trie{
int count;
unordered_map <char,trie*> next;
};
and it works.
Is there any disadvantage for unordered_map than arr[26]?
Share Improve this question edited Jan 20 at 11:55 Bizzle 11712 bronze badges asked Jan 20 at 11:32 유정현유정현 412 bronze badges 13 | Show 8 more comments1 Answer
Reset to default 3Not sure why this is downvoted, because it's a valid question, and there seems to be no duplicate question yet.
A std::unordered_map<char, trie*>
will take sizeof(std::unordered_map<char, trie*>)
bytes of memory in the trie
object itself, independent of std::unordered_map<char, trie*>::size()
. In addition, it will take a several extra bytes per trie*
in that std::unordered_map
. 16 or 32 bytes per entry would be perfectly normal.
So it's very well possible that it takes more bytes in memory than that trie*[26]
. Even if it did save memory, the trie*[26]
has an additional advantage of being contiguous in memory, quite possible on a single cache line. It's also a bit simpler and uses less instructions in the compiler executable.
std::unordered_map
is)? Simplicity? – Some programmer dude Commented Jan 20 at 11:42