STL: How to write a custom key to a hashmap

Sep 29, 2004
18,656
67
91
Before I forget, we're using Visual Studio (not sure what version).

Basically, I want to use two integers (int) as a key to a hashmap.

Can someone explain how I would write a custom key for a hashmap in STL.

Thanks.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Here is something straight from cppreference.com:
struct strCmp {
bool operator()( const char* s1, const char* s2 ) const {
return strcmp( s1, s2 ) < 0;
}
};

...

map<const char*, int, strCmp> ages;
ages["Homer"] = 38;
ages["Marge"] = 37;
ages["Lisa"] = 8;
ages["Maggie"] = 1;
ages["Bart"] = 11;

cout << "Bart is " << ages["Bart"] << " years old" << endl;

To change the key to two integers, do this:

struct twoIntKey {
int key1;
int key2;
}

struct twoIntCmp {
bool operator()( const twoIntKey s1, const twoIntKey s2 ) const {
return /* some boolean expression that does what you want */
}
};

.
.
.

map<twoIntKey, /*whatever*/, twoIntCmp> foo;
 

Venix

Golden Member
Aug 22, 2002
1,084
3
81
You could also define bool operator<(const twoIntKey& other) const in your twoIntKey struct so you won't need that third template parameter.

And just so you know, map is actually a balanced binary tree, not a hash. If you need an actual hash you can use stdext::hash_map or unordered_map. unordered_map is part of the C++ TR1 standard, but it's only included in Visual Studio 2008.
 

degibson

Golden Member
Mar 21, 2008
1,389
0
0
Map is an interface. How it is actually implemented depends on your C++ library.
 

Venix

Golden Member
Aug 22, 2002
1,084
3
81
STL is much more than just interfaces--a standards-compliant container must also meet numerous implementation requirements.

map models the Unique Sorted Associative Container concept, which imposes asymptotic complexity constraints and requires ordering of elements. The latter requirement eliminates hash tables as a possible implementation, and the former demands either a balanced binary tree or a structure with identical performance characteristics.

And anyway, this thread is about Visual Studio, which implements map as a red-black tree.
 

hans007

Lifer
Feb 1, 2000
20,212
18
81
you could just take the 2 ints and join them into 1 string. ints are 4 bytes so unsigned they are only 5 digits. so your key would be 10 digits with leading 0s on the ints.



i've been told some firewalls do this fire firewall port rule hashes and it is quite fast. port numbers for inbound and outbound are 2 ints after all.