2016-04-15 58 views
-2

我想排序一個有一個鍵作爲字符串,並有一個無符號long long對,當我使用sort()方法從#include我試圖過載加載<運算符,但是當我通過地圖和結束的開始地址我無法訪問map.first,map.second.first,或map.second.second使用一個鍵和一對值對地圖進行排序?

沒有任何人有任何想法

map<string, pair<unsigned long long, unsigned long long>> ext_count; 
    sort(map.rbegin(), map.rend()); // to sort descending 
bool operator < (map<string, pair<unsigned long long, unsigned long long>>& lhs, map<string, pair<unsigned long long, unsigned long long>>& rhs) { 
return lhs.first < rhs.first; 

}

+2

嗯,地圖是一個排序的容器。您無法對地圖進行排序 – NathanOliver

+1

地圖是有序的容器,不能被「排序」 - 您只能定義一個排序順序,該排序順序將始終用於此地圖。 – SergeyA

+0

那麼我將如何更改排序順序? – Nikes

回答

0

正如評論所建議的,一種方法是將地圖複製到具有不同排序順序的地圖上。

這裏是實現這個的一個小例子:我們使用的是第三個參數的std::map聲明指定分揀機謂詞

#include <map> 
#include <string> 
#include <algorithm> 
#include <iterator> 

// define the Sorter template class. If sortdir == true, then we sort ascending 
template <bool sortdir = true> 
struct Sorter 
{ 
    bool operator()(const std::string& left, const std::string& right) 
    { 
     if (sortdir) 
      return left < right; 
     return left > right; 
    } 
}; 

// our test maps 
typedef std::pair<unsigned long long, unsigned long long> mapDataType; 

// ascending map 
std::map<std::string, mapDataType, Sorter<>> myMap = 
          {{"abc", {0,0}}, {"def",{0,1}}}; 

// descending map 
std::map<std::string, mapDataType, Sorter<false>> myMap2; // descending map 

// sample program 
using namespace std; 
int main() 
{ 
    // copy ascending map to descending map 
    std::copy(myMap.begin(), myMap.end(), 
       std::inserter(myMap2, myMap2.begin())); 
} 

注意。

此外,std::copy函數用於將所有元素從源地圖簡單複製到目標地圖。

Live Example

相關問題