[英]Why can't I sort a map by values using a function?
我正在尝试按值对地图进行排序。 我研究了如何执行此操作,并得到了以下代码。 但是,它不会编译,我不确定为什么。
#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;
}
std::map
始终按键排序。 您需要先转换为对列表,然后再对列表进行排序。 说到这一点, std::sort
根据其原型需要随机迭代器:
template< class RandomIt >
void sort( RandomIt first, RandomIt last );
随机迭代器意味着std::sort
应该能够以任何索引访问元素(即,用于交换元素1和3)。 但是,索引访问对映射没有任何意义,因为它是通过键而不是索引访问的。
例:
std::list<std::map<int,int>::value_type> list;
std::copy(myMap.begin(), myMap.end(), std::back_inserter(list));
list.sort(cmp);
错误的另一个(技术上)可能的原因(除了在语义上是胡说八道,而且映射迭代器不是随机变量,如@myaut所说)是map
(和unordered_map
)基础值类型。 在您的情况下,它实际上是std::pair<const int, int>
。 所以:
sort
也会尝试移动值并为其分配值。 而且您不能分配给const
变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.