[英]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.