2016-11-07 47 views
0

說我定義我的元組如下:自定義排序有序地圖元組作爲鍵

typedef tuple<string, string> bigram; 

我的地圖的地圖元組的整數:

map<bigram, int> mymap; 

我怎麼能定製我的比較,這樣mymap按照bigram中第一個字符串的字母順序排序?

我沿着

map<bigram, int, greater<bigrams[0]>> mymap; 

回答

2

第一 - 按字母順序排列意味着你要less,而不是greater。其次,tuple<string, string>的默認排序順序應該適合您。注意:人們提出的各種建議可能不會做你想做的事。當你可能希望將它們視爲不同的對象時,它們都將{"foo", "bar"}{"foo", "baz"}相比較。如果你想反向排序,你應該可以做map<bigram, int, std::greater<bigram>>否則堅持只是map<bigram, int>

,以供參考比較運算符來免費使用數組的定義:http://en.cppreference.com/w/cpp/utility/tuple/operator_cmp

1

線某處思維定義一個比較無論是作爲一個函數或函數對象,並傳遞:

bool comparator(const bigram& a, const bigram& b) 
{ 
    ... 
} 
std::map<bigram, int, comparator> map; 

比較應該返回,如果參數真已經訂購了(a在b之前)。

1

它可以這樣實現:

typedef std::tuple<std::string, std::string> bigrams; 

struct bigrams_comp { 
    bool operator()(const bigrams& lhs, const bigrams& rhs) { 
     // return std::greater<std::string>()(std::get<0>(lhs), std::get<0>(rhs)); 
     return std::get<0>(lhs) > std::get<0>(rhs); 
    } 
}; 

int main() 
{ 
    std::map<bigrams, int, bigrams_comp> mymap; 
} 
+0

'std :: greater'的任何原因?爲什麼不'std :: get <0>(lhs)> std :: get <0>(rhs)'? – Rakete1111

+0

@ Rakete1111因爲他在他的問題中使用更多 – Danh

0

您使用的雙字母組,但定義兩字,不是一個錯字?

比較函數類型必須比較兩個鍵類型返回一個布爾值。

struct MyCompare 
{ 
    bool operator()(const bigram &a, const bigram &b) 
    { 
     return std::get<0>(a) > std::get<0>(b); 
    } 
}; 

map<bigram, int, MyCompare> mymap; 
1

如果你想有一個正確的比較,你必須檢查的元組的每個部件。

對於我這個好答案是:

typedef std::tuple<std::string, std::string> bigrams; 

    struct bigrams_comp { 
     bool operator()(const bigrams& lhs, const bigrams& rhs) { 
      if (std::get<0>(lhs) == std::get<0>(rhs)) { 
       return std::get<1>(lhs) > std::get<1>(rhs); 
      } else { 
      return std::get<0>(lhs) > std::get<0>(rhs); 
      } 
     } 
    }; 

否則二進制搜索的地圖將是錯誤的。

告訴我,如果我錯了。