2016-04-15 7 views
-2

私は文字列としてキーを持つマップをソートしようとしています。そして、#includeからsort()メソッドを使用すると、符号なしlong longを持つペアがあります。<演算子をオーバーロードしようとしていますが、マップの最初と最後のアドレスiのmap.second.first、map.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

um、マップはソートされたコンテナです。 – NathanOliver

+1

マップは順序付けされたコンテナです。これは 'ソートできません 'です。ソート順は1つしか定義できません。このソート順は常にこのマップで使用されます。 – SergeyA

+0

どうすればソート順を変更できますか? – Nikes

答えて

0

提案されたコメントが示すように、1つの方法は、異なるソート順のマップにマップをコピーすることです。我々はソータ述語を指定する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

関連する問題