c++ - 在 C++ 中的 unordered_map 中排序

标签 c++

所以我有一个数组:

arr[] = {5, 2,4,2,3,5,1};

如何按照它们在 unordered_map 中出现的次数按此顺序插入它们?

#include<bits/stdc++.h>

using namespace std;

void three_freq(int arr[], int n){
    unordered_map<int, int> m;

    for(int i=0;i<n;i++){
        m[arr[i]]++;
    }

    for(auto itr = m.begin(); itr != m.end(); itr++){
        cout<<itr->first<<":"<<itr->second<<"\n";
    }

}

int main(){
    int arr[] = {5, 2,4,2,3,5,1};
    int n = sizeof(arr)/ sizeof(arr[0]);
    three_freq(arr, n);
    return 0;
}

使用上面的代码,我得到的输出是:

1:1
3:1
4:1
5:2
2:2

但我希望输出与元素在数组中出现的顺序相同。 示例:

5:2
2:2
4:1
3:1
1:1

最佳答案

如果您不关心效率(那么多),那么您可以只更改打印输出的 for 循环。

for(int i=0; m.size(); i++) {
   auto it = m.find(arr[i]); 
   if (it != m.end()) {
      cout<<arr[i]<<":"<<it->second<<"\n";
      m.erase(it);
    }
} 

关于c++ - 在 C++ 中的 unordered_map 中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69406741/

相关文章:

c++ - c++中具有奇数和偶数指数的多项式函数

c++ - OpenGL 会阻止不必要的 API 调用吗?

c++ - 当 KEY 为 boost::optional 参数时用于 boost 多索引的迭代器

c++ - C++ 中 char* 类型的变量

c++ - 对堆的访问是否序列化?

c++ - 无法将 'idt_entry_t (*)[256] 转换为 u8int*

c++ - 在静态变量定义中捕获的引用

c++ - 构造函数中的智能指针

c++ - 如何使用 C++ 获取 LAN 网络上 IP 摄像机的所有 MAC 地址和端口号?

c++ - boost 最佳实践?