VC8 的 hash_map
刚刚装上VC8,发现VC8现在也支持hash_map了,终于可以不用STLPort了(不是不想用,而是在VC里面用太TNND麻烦了)。不过VC8上的hash-map还是有不爽的地方 1。它定义在stdext namespace 中 2。它需要至少specialize两个template来添加自定义类。。。不过终究还是算不小的的进步啦;D =====================================
============ VC2005 ================
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
#include
#include
struct Key{
int i;
};
namespace std {
template <> struct less<::Key>
: public binary_function<::Key, ::Key, bool>
{
bool operator()(const ::Key& _Left, const ::Key& _Right) const
{ // apply operator< to operands
return (_Left.i < _Right.i);
}
};
}
namespace stdext {
template <> size_t hash_value (const Key &key){
return hash_value (key.i);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
stdext::hash_map testmap;
Key k;
k.i = 1;
testmap[k] = std::string("hello, world");
testmap[k] = std::string("hello, again");
std::cout << "size of map: " << testmap.size() << std::endl;
return 0;
}
============GCC + STLPort ===========
struct Key {
...
};
namespace std {
template <> struct hash {
size_t operator()(const Key &key) const {
...
};
}
}
int main()
{
...
}