我必须研究 HashMap 实现。我研究过它会根据模板中提到的顺序对元素进行排序。示例代码是:
#include <hash_map>
#include <iostream>
using namespace std;
int main()
{
typedef pair <int, int> Int_Pair;
hash_map <int, int>::iterator hmp1_Iter;
hash_map <int, int , hash_compare <int, less<int> > > hmp1;
hmp1.insert(Int_Pair(1, 13));
hmp1.insert(Int_Pair(3, 51));
hmp1.insert(Int_Pair(7, 22));
hmp1.insert(Int_Pair(2, 31));
cout<<"\nOperation1: hash_map<int, int, \nhash_compare<int, less<int> > > hmp1\n";
cout<<"Operation2: hmp1.insert(Int_Pair(1, 13))...\n";
cout<<"hmp1 data: ";
for(hmp1_Iter = hmp1.begin(); hmp1_Iter != hmp1.end(); hmp1_Iter++)
cout<<hmp1_Iter->first<<":"<<hmp1_Iter->second<<" ";
cout<<endl;
return 0;
}
代码的预期结果是:1:13 2:31 3:51 7:22 但它给出了 1:31 3:51 7:22 2:31 。但是应该按升序排列关键元素。请解释为什么会这样?
最佳答案
std::hash_map
是一个无序的关联容器,通常用散列表(键的散列作为链表数组中的索引)实现
如果你需要一个“有序 HashMap ”,你可以使用一个std::map
。它通常是一棵红黑树,其关键元素可以按升序迭代。
std::hash_map
在插入和删除时应该比 std::map
更快。
关于c++ - C++ 中的 Hashmap 不对元素进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878727/