0

假设我有: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;

但我得到了很多编译错误。我在这里做错了吗?

4

2 回答 2

2

我想它必须是这样的:

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;
//                      ^^^^^^^

在这里,您可以看到上述代码编译的实时示例。

于 2013-03-30T21:05:24.463 回答
1

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;
}

You can see that I've also made your comparator arguments const references, just for the sake of it really.

于 2013-03-30T21:34:21.097 回答