c++ - 为什么我不能使用函数按值对 map 进行排序?

标签 c++ dictionary

我正在尝试按值对 map 进行排序。我做了一个关于如何做的研究,最后得到了以下代码。但是,它不会编译,我不确定为什么。

#include <iostream>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;

bool cmp(pair<int,int> const & a, pair<int,int> const & b)
{
    return a.second != b.second?  a.second < b.second : a.first < b.first;
}

int main()
{
map<int,int>myMap;
for(int i=0,j=10;i<10;i++,j--)
{
    myMap.emplace(i,j);
}
for(map<int,int>::iterator it=myMap.begin();it!=myMap.end();it++)
{
    cout <<  it->first << " " << it->second << endl;
}

sort(myMap.begin(),myMap.end(),cmp);

for(map<int,int>::iterator it=myMap.begin();it!=myMap.end();it++)
{
    cout <<  it->first << " " << it->second << endl;
}
    return 0;
}

最佳答案

另一个(技术上的)可能的错误原因(除了它在语义上是无意义的,并且映射迭代器不是随机的,正如@myaut 所说)是 map (和 unordered_map )基础值类型。在您的情况下,它实际上是 std::pair<const int, int> .所以:

  • 你的比较函数不会接受它(它会尝试将引用绑定(bind)到错误的类型)
  • 即使你修好了,sort将尝试移动值,分配它们。而且你不能分配给 const变量

关于c++ - 为什么我不能使用函数按值对 map 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42872913/

相关文章:

c++ - 派生类的五法则

c++ - 如何将 ATL/MFC CString 转换为 QString?

python - 如何在不循环的情况下检查字典列表中是否存在任何反向元素

arrays - Swift 3.0 删除字典数组中的重复项

c# - 字典中类型的自定义相等比较器

C# 字典 : making the Key case-insensitive through declarations

c++ - g++4.9 错误允许 std::vector<C_type_array>

c++ - 线段树实现中的问题

c++ - 如果该分隔符包含在方括号中,我如何通过分隔符拆分 QString 而不是

java - 在LWUIT中创建离线 map 应用程序