Reputation: 205
I'm using strings as a type of key for my unordered_map
but is it possible that I could associate a secondary unique key, independent from the primary, so I could perform a find operation with the second key?
I was thinking that the key could be a hash number the internal hash algorithm came up with.
I thought of including an id (increasing by 1 each time) to the structure I'm saving but then again, I would have to look up for the key that is a string first.
Reason behind this: I want to make lists that enlist some of the elements in the unordered_map
but saving strings in the list is very inefficient instead of saving int
or long long
. (I would prefer not to use pointers but rather a bookkeeping style of procedure).
Upvotes: 1
Views: 262
Reputation: 1900
You couldn't use a hash number the internal hash algorithm came up with because it could change the numbers due to the table growth in size. This is called rehashing. Also hashes are not guaranteed to be unique (they certainly won't be).
Keeping pointers to elements in your list will work just fine, since unordered_map
doesn't invalidate pointers. But the deletion of the elements will be hard.
Boost has multi_index_container
, which provides many useful database-like functions. It will be perfect for your task.
If you don't want to use Boost, you could use unordered_map
with unique integer indices, and another unordered_map
which keeps string->index
pairs for searching by string keys. The deletion will also be hard, because either you will check all your lists each time you delete a record, or you will check if the record still exists each time you are traversing the list.
Upvotes: 2