#include <iostream>
#include <map>
#include <utility>
#include <algorithm>
int main()
{
std::map<int, std::string> m;
m[2] = "abc";
m[1] = "bcd";
auto cmp = [](std::pair<int, std::string> a, std::pair<int, std::string> b)
{
return a.second != b.second ? a.second < b.second : a.first < b.first;
};
std::sort(m.begin(), m.end(), cmp);
for (auto it = m.begin(); it != m.end(); ++it)
{
std::cout<<it->first<<std::endl;
std::cout<<it->second<<std::endl;
}
return 0;
}
我想按值而不是键对 map 进行排序,因此我按上面的代码进行编码。
我刚刚阅读了这个链接,这就是我编写这样的代码的原因:std::map, how to sort by value, then by key
但是它产生了一个错误:
Severity Code Description Project File Line Suppression State
Error C2784 'unknown-type std::operator -(const std::move_iterator<_RanIt> &,const std::move_iterator<_RanIt2> &)': could not deduce template argument for 'const std::move_iterator<_RanIt> &' from 'std::_Tree_unchecked_iterator<_Mytree>' testcpp c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.10.25017\include\algorithm 2908
最佳答案
auto cmp = [](std::pair<int, std::string> a, std::pair<int, std::string> b)
{
return a.second != b.second ? a.second < b.second : a.first < b.first;
};
问题来了。
谓词的参数应该是 key_type
可以隐式转换的类型
并且您不应该将std::sort
应用于std::map
。一个原因是此操作冗余(请参阅下面的引用资料),另一个原因是key
具有const
类型。
http://en.cppreference.com/w/cpp/container/map
还有一个建议:
将谓词的参数类型声明为对 const 的引用
关于c++ - 为什么我不能使用 lambda 按值对 std::map 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49955374/