stdext :: hash_map不清楚哈希函数

时间:2013-07-08 14:09:51

标签: c++ hashmap

#include <iostream>
#include <hash_map>

using namespace stdext;
using namespace std;

class CompareStdString
{
public:
bool operator ()(const string & str1, const string & str2) const
    {
        return str1.compare(str2) < 0;
    }
};
int main()
{
    hash_map<string, int, hash_compare<string, CompareStdString> > Map;
    Map.insert(make_pair("one", 1));
    Map.insert(make_pair("two", 2));
    Map.insert(make_pair("three", 3));
    Map.insert(make_pair("four", 4));
    Map.insert(make_pair("five", 5));
    hash_map<string, int, hash_compare<string, CompareStdString> > :: iterator i;
    for (i = Map.begin(); i != Map.end(); ++i)
    {
        i -> first; // they are ordered as three, five, two, four, one
    }
    return 0;
}

我想使用hash_map将std :: string作为键。但是当我插入下一对订单时很困惑。为什么订单与插入订单不匹配?我应该如何获得订单一二三四五?

1 个答案:

答案 0 :(得分:0)

  

为什么订单与插入订单不匹配?

那是因为stdext::hash_map(以及C ++ 11中与平台无关的标准库版本std::unordered_map)没有维护/保证其元素的任何合理顺序,甚至没有插入订单。这是因为它是一个散列的容器,具有各个元素&#39;基于其哈希值的容器大小的位置。因此,您无法使用此类容器维护合理的数据订单。

您可以使用什么来保证您的元素保证顺序是一个很好的旧std::map。但是这也不是按插入顺序排序元素,而是按照比较谓词引起的顺序排序(这可以用于尊重插入时间,但这将非常不直观而且根本不容易)。

对于你赢得的任何其他事情,你可以自己动手(或者搜索其他图书馆,不知道是否有类似的东西)。例如,为了插入顺序迭代,将所有元素添加到线性std::vector / std::list,并为O(1)/ O(log n)检索维护指向该向量/列表的附加std::(unordered_)map如果有必要的话。

相关问题