【发布时间】:2010-10-25 19:59:10
【问题描述】:
C++,使用 Visual Studio 2010。关于为什么hash_map 的用户定义特征实际上需要全排序的问题。
我有一个简单的结构,比如FOO,它只有多个整数。我想使用hash_map,它是一个散列表,其键是无序,来存储FOO 的结构。我只需要快速搜索它的关联值,所以这是一个正确的选择:hash_map<FOO, int32_t>。
但是,我需要为FOO 实现自己的哈希函数和一些比较函数。这是hash_map的定义,取自MSDN:
template <
class Key,
class Type,
class Traits=hash_compare<Key, less<Key> >,
class Allocator=allocator<pair <const Key, Type> >
>
class hash_map
原来我需要实现hash_compare函子:
template<class Key, class Traits = less<Key> >
class hash_compare
{
Traits comp;
public:
const size_t bucket_size = 4;
const size_t min_buckets = 8;
hash_compare( );
hash_compare( Traits pred );
size_t operator( )( const Key& _Key ) const; // This is a hash function
bool operator( )( // This is an ordering function
const Key& _Key1,
const Key& _Key2
) const;
};
这里是来自 MSDN 的 bool operator() 的详细描述:
对于序列中在 _Key2 之前且具有相同散列值(散列函数返回的值)的任何Key 类型的值_Key1,hash_comp(_Key2, _Key1) 为假。该函数必须对 Key 类型的值施加总排序。hash_compare 提供的函数返回 comp(_Key2, _Key1),其中 comp 是 Traits 类型的存储对象,您可以在构造对象 hash_comp 时指定该对象。对于默认的 Traits 参数类型 less,排序键的值永远不会减少。
为FOO 编写hash_compare 类很容易。这个问题不是询问如何实现一个类。但是,对我来说,为什么它们的默认 trait 参数为 less<key> 并需要总排序对我来说并不简单。
hash_map 是一个 无序 数据结构。所以,我认为拥有equal_to 或not_equal_to 而不是less 或greater 就足够了。但是,MSDN 的描述明确指出键是有序的,这让我感到困惑。
我是不是误解了hash_map的定义?为什么 STL 的 hash_map 实际上需要它的 key 的命令?
【问题讨论】:
标签: c++ data-structures stl