【发布时间】:2018-10-01 23:33:35
【问题描述】:
#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;
}
我想按它的值而不是它的键对地图进行排序,所以我按照上面的代码进行编码。
我刚刚阅读了这个链接,这就是我这样编码的原因: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
【问题讨论】:
-
你应该重新阅读链接。
-
请注意,链接的问题排序为
vector,而不是map。地图已按键排序以支持快速查找,并且无法重新排序。 (具体的错误信息来自std::sort,需要一个随机访问迭代器,而地图没有)。 -
std::map是一个排序容器;并按key排序(第一种类型的pair);您可以更改排序功能(使用std::map的第三个默认模板参数),但使用std::sort对其进行排序没有任何意义。
标签: c++ sorting c++11 dictionary