Hash_map

Aug 4, 2010 at 8:49am
Hello everyone.
I have been trying to make hash using hash_map.
The problem is that I have to insert in the hash_map more keys with the same value

For example:
int a[100];
a[1]=100;
a[2]=90;
a[3]=100;
for(i=1;i<=3;i++)
H[a[i]]=i;
So in H[100] I must insert 2 indices.
Can anyone tell me how can I find out wich are the indices of the elements in array a[] that have some value x using the hash_map.
I will appreciate also answers about how to use map instead of using hash_map.

Aug 9, 2010 at 10:34am
If you want to retain previous values you inserted, then you want something a bit more complicated than a simple hash map.

Instead of holding a single value, you need a container. Adding involves appending to the container. But you're still left with the problem of determining whether a given index is valid.

If you use iterators instead of an index, you can use check for validity.
1
2
3
4
5
6
7
8
9
iter = a.find(100);
if (iter != a.end())
{
    // 100 is a valid index
}
else
{
    // 100 is not a valid index
}
Aug 9, 2010 at 12:45pm
I'm no expert, but 2 things spring to mind.

If you are attempting to store keys which are the same, then you want a multimap (hash_multimap / unordered_multimap)

1
2
3
4
5
6
7
hash_map<int, foo> m;
m.insert(pair<int, foo>(0, my_foo_1));
m.insert(pair<int, foo>(0, my_foo_2)); // won't be inserted - key=0 already exists

hash_multimap<int, foo> m;
m.insert(pair<int, foo>(0, my_foo_1));
m.insert(pair<int, foo>(0, my_foo_2)); // multiple keys with same value can exist 


If you are attempting to store unique keys where the associated value for each key could be the same, and you want to find out which keys are associated with matching values, you will have to use one of the std algorithms

I don't think equal_range will work for you, since it requires a sorted range, whereas by their very nature hash_maps are not sorted. That means you're probably limited to for_each using a predicate which compares against the value part of the pair associated with each element in your hash_map.

Topic archived. No new replies allowed.