2017-03-18 212 views
0

我想按值排序地圖。我做了一個關於如何去做的研究,最終得到了下面的代碼。但是,它不會編譯,我不知道爲什麼。爲什麼我不能使用函數對值進行排序?

#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; 
} 
+0

請與我們分享編譯錯誤。 –

+0

這很長,但確定。讓我添加它。編輯:它讓我補充一些細節,因爲我的文章主要是代碼。這沒有意義。 @RichardCritten – zeke

+3

'std :: map'總是按鍵排序。你需要首先轉換成對列表然後排序列表 – myaut

回答

1

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); 
+0

我明白了。在這種情況下'map :: iterator'是雙向的。因此錯誤。 – zeke

+0

它不需要是'std :: list'。它也可以是'std :: vector',在這種情況下'std :: find'會被使用。 –

1

的誤差的(除了它是無義語義和地圖迭代器是不是隨機的,如@myaut所述)另一個(技術)可能的原因是map(和unordered_map)底層值類型。在你的情況下,它實際上是std::pair<const int, int>。所以:

  • 你比較函數不會接受它(它會嘗試綁定參考錯誤類型)
  • 即使你修復它,sort會嘗試走動值,分配他們。並且您不能指定const變量
相關問題