John Ratcliff's Code Suppository

A place where I insert my code into the anus of the Internet.

 

Saturday, June 16, 2007

Hash Map stdext::hash_map



I know I haven't posted anything in a while; what can I say, I've been busy. Recently I had to turn in a deadline for a book chapter in AI Wisdom 4. In doing so I wrote a few new snippets and I thought I would take this afternoon to publish them.

The first snippet is just a simple template class that demonstrates the most common usage of an STL hash_map. Semantically a hash_map works pretty much just like a regular STL map but instead of using a red-black tree it maintains a hash table which allows most lookups to be retrieved in a single step. So long as you don't need to retain a specific ordering for a container, simply needing fast random access, then a hash_map is always the best way to go.

Pretty much the most common usage of a hash_map is to associate some integer key (often a GUID) with a pointer to a class. I made a small template that implements this most common usage in a fairly simple API. It is called 'IntPtr'.

For example, if you wanted to map a set of integers to a set of pointers to a class called 'Foo' you would declare it as follows:

IntPtr<> mFooHash;

To look up an instance of class Foo by a value you would say: Foo *f = mFooHash.get(v);
To make an association between a Foo pointer and an interger it would be:

mFooHash.set(foo,v);

To iterate the container you would say:

Foo *f = mFooHash.begin();
while( f )
{
f = mFooHash.next();
}

There is no specific destructor for this template and it assumes you own the memory associated with the 'Foo' pointers. You must remember to destruct them yourself. There is another version of the template called 'IntInt' which just provides a mapping between one integer type and another.

I have been informed, by someone I trust knows what he is talking about, that you can use 64 bit long integers in an STL hash_map and they are guaranteed to be unique. This can be quite useful when associated very large GUIDS with pointers to a class.

If you have never messed around with the STL hash_map container this is a good place to begin experimenting with it. It is a very powerful container and is extremely fast.

Here is a link to the source and I will also update the repository page.

intptr.h

0 Comments:

Post a Comment

<< Home