c++ - C++ 中的 Hashmap 不对元素进行排序?

标签 c++ hashmap

我必须研究 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/

相关文章:

c++ - 如果我指定多个,则使用哪个 `main`

Python 对 Qt dll 的支持

Java:从 HashMap 读取可以改变其状态吗?

java - 比较 Java 中的 HashMap

java - 如何为每个 RDD Spark Streaming

java - 迭代 HashMap 以将 JMenuItem 添加到 JMenu

c++ - 我在使用 z3 :timeout correctly with C++ interface for Linux?

c++ - QObject::sender() 在插槽中无法正常工作

c++ - 使用 find_if 查找结构内部的 int for std::list with structs

java - 按键升序排序 map