Friday, March 27, 2009


Well I was looking for a hash-map in C++ since doing something like


Where myMap is an std::map<> takes logarithmic look up.

So after some looking around I did manage to find that there were hash-maps for C++, but after that I had to do some more searching to see what libraries I needed to include in order to use them.

Below is a little program that just prints the integers 1 to 10 followed by hello world, that makes use of a hash-map.

using namespace std;
using namespace __gnu_cxx;

int main()
hash_map<int,int> myhash;
for(int i=0;i<10;i++)
for(typeof(myhash.begin()) i=myhash.begin();i!=myhash.end();i++)
cout<<i->second<<' ';
cout<<"hello world\n";
return 0;

Certainly not the most user friendly stuff to type at the beginning but I suppose it is worth it. I should mention that when I wrote the second for loop I had no idea if it would compile or not since I didn't know that you could use iterators on hash_maps. Also unlike std::map, __gnu_cxx::hash_map does not store the keys in an ordered fashion, just something to be aware of.

As a side note, if you didn't add the line

using namespace __gnu_cxx;

you would have to type


This should be obvious but you never know when/if you'll one day forget.

No comments: