tags:

views:

98

answers:

2

Hi all,

I have two questions about Google's dense_hash_map, which can be used instead of the more standard unordered_map or hash_map:

  1. 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.

  2. 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

+2  A: 

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.

anon
Thanks! However, I need it to point to an existing char * pointer in memory instead of copying it and displacing it. Would it be possible with it?
Shlomi Fish
@shlomif You really do not want to do that - it is much better to copy the key. If you feel you must do that, I would implement my own key class to encapsulate it.
anon
I second Neil's objection. The reason you don't want to do this is that the data your char* points to may be changed after it is added to the hash and then it will have a different hash value so you won't be able to look it up. If you absolutely know that the data will never change, then you can get away with it...but it is asking for trouble.
A. Levy
+2  A: 

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()`
Matthieu M.
@Matthieu Yes, that's true - I'll edit my answer.
anon