关于hash_map的使用和自定义类型
执假以为真 2007-07-29 11:04:09 上网找了很多资料,包括下面的连接等等:
http://www.stlchina.org/twiki/bin/view.pl/Main/STLDetailHashMap
写了个原型程序,但是打印的结果却不对,不知道为什么,请各位高手指点迷津!谢谢!
#include <iostream>
#include <hash_map>
#include <string>
using namespace std;
using stdext::hash_map;
class FenItem
{
public:
string fen;
string move;
enum {bucket_size = 1000, min_buckets = 1000 }; //何意?
public:
unsigned long operator () (const FenItem& f) const
{
char array[120];
memset(array, '\0', 120);
strncpy(array, (string(f.fen+f.move)).c_str(), strlen((string(f.fen+f.move)).c_str()));
size_t nKeyLength=strlen(array);
unsigned long h = 0, g;
char *arKey=array;
char *arEnd=arKey+nKeyLength;
while (arKey < arEnd)
{
h = (h << 4) + *arKey++;
if ((g = (h & 0xF0000000)))
{
h = h ^ (g >> 24);
h = h ^ g;
}
}
return h;
}
bool operator () (const FenItem& f1, const FenItem& f2) const
{
return ((f1.fen+f1.move) == (f2.fen+f2.move));
}
};
typedef hash_map<FenItem, int, FenItem> FenMap;
void main()
{
FenMap fm;
FenItem f1, f2;
f1.fen="Hello"; f1.move="World";
f2.fen="EE"; f2.move="FF";
fm[f1]=9; fm[f2]=20;
cout<<fm[f1]<<" "<<fm[f2]<<endl;
}