簡體   English   中英

如何為地圖編寫可選的比較函子?

[英]How do you write the optional comparison functor for a map?

假設我有: map<map_data, int, decltype(compare)> the_map

struct map_data{
   int data1;
   int data2;
}

我試着將比較寫為:

struct
{
   bool operator()(map_data one, map_data two) const
   {
      if(one.data1 == two.data1)
         return one.data2 > two.data2;
      else
         return one.data1 < two.data1;
   }
}compare;

但是我遇到很多編譯錯誤。 我在這里做錯什么了嗎?

我想那一定是這樣的:

struct compare
{
   bool operator()(map_data const& one, map_data const& two) const
   {
      if(one.data1 == two.data1)
         return one.data2 > two.data2;
      else
         return one.data1 < one.data2;
   }
};

另外,您不需要decltype 直接使用函子類的名稱:

std::map<map_data, int, compare> the_map;
//                      ^^^^^^^

在這里,您可以看到上述代碼編譯的實時示例

您忘記了map_data定義后的分號。 修復此問題,可以在C ++ 11中成功編譯

#include <map>

using std::map;

struct map_data{
   int data1;
   int data2;
};

struct
{
   bool operator()(map_data one, map_data two) const
   {
      if(one.data1 == two.data1)
         return one.data2 > two.data2;
      else
         return one.data1 < two.data1;
   }
}compare;

int main() {
    map<map_data, int, decltype(compare)> the_map;
}

但是,為此需要C ++ 11 decltype並在您真正需要的只是類型時實例化一個對象compare似乎有點浪費。

為什么不習慣

#include <map>

using std::map;

struct map_data {
   int data1;
   int data2;
};

struct map_data_comparator
{
   bool operator()(const map_data& one, const map_data& two) const
   {
      if (one.data1 == two.data1)
         return one.data2 > two.data2;
      else
         return one.data1 < two.data1;
   }
};

int main()
{
    map<map_data, int, map_data_comparator> the_map;
}

您可以看到,我確實也為比較器參數設置了const引用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM