C++'s unordered_map / hash_map / Google's dense_hash - how to input binary data (buf+len) and insert operation
I have two questions about Google's dense_hash_map, which can be used instead of the more standard unordered_map or hash_map:
How do I use an arbitrary binary data memory segment as a key: I want a buffer+length pair, which may still contain some NUL (\0) characters. I can see how I use a NUL-terminated char * string , but that's not what I want.
How do I implement an operation where I look if a key exists, and if not - insert it and if it does return the pointer to the existing key and let me know what actually happened.
开发者_如何学运维
I'd appreciate it if anyone can shed any light on this subject.
Regards,
-- Shlomi Fish
I would disagree with Neil.
I would use insert
for number 2. Using find
then insert
causes 2 look-ups while using insert
causes one look-up without overriding if the element is already present. Normally, insert
returns an iterator to the key/value pair corresponding (even if not updated) + a boolean which indicates whether or not the insertion took place.
std::pair<iterator, bool> result = map.insert(std::make_pair(key(), value());
result.first->second; // accesses the value at key: `key()`
For #1, use a std::string
as the key - std::strings can contain embedded NUL characters with no problems. For #2, see Matthieu's answer.
精彩评论