为一对中的一个元素提供小于运算符 [英] Providing less than operator for one element of a pair

查看:135
本文介绍了为一对中的一个元素提供小于运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最优雅的方式,以修复以下代码:

What would be the most elegant way too fix the following code:

#include <vector>
#include <map>
#include <set>
using namespace std;

typedef map< int, int > row_t;
typedef vector< row_t > board_t;
typedef row_t::iterator area_t;

bool operator< ( area_t const& a, area_t const& b ) {
    return( a->first < b->first );
};

int main( int argc, char* argv[] )
{
    int row_num;
    area_t it;

    set< pair< int, area_t > > queue;
    queue.insert( make_pair( row_num, it ) ); // does not compile
};

一种解决方法是移动less& to
namespace std(我知道,   你不应该这样做。

One way to fix it is moving the definition of less< to namespace std (I know,  you are not supposed to do it.)

namespace std {
    bool operator< ( area_t const& a, area_t const& b ) {
        return( a->first < b->first );
    };
};

另一个明显的解决方案是定义小于< for
pair< int,area_t>但是我想避免这样,并且
只能为未定义的对的一个元素
定义运算符。

Another obvious solution is defining less than< for pair< int, area_t > but I'd like to avoid that and be able to define the operator only for the one element of the pair where it is not defined.

推荐答案

当你实现一个比较器实现一些特定和/或相当奇怪的比较方法,最好使用命名的函数或函数对象,而不是劫持运算符< 。我会说,比较一个 std :: pair 对象的自然方式是使用词典比较。由于您的比较不是字典编码,接管运算符<可能不是一个好主意。更好地实现比较器类

When you are implementing a comparator that implements some specific and/or fairly exotic comparison approach, it is better to use a named function or a function object instead of hijacking the operator < for that purpose. I'd say that the natural way to compare a std::pair object would be to use lexicographical comparison. Since your comparison is not lexicographical, taking over operator < might not be a good idea. Better implement a comparator class

typedef pair< int, area_t > Pair; // give it a more meaningful name

struct CompareFirstThroughSecond {
  bool operator ()(const Pair& p1, const Pair& p2) const { 
    if (p1.first != p2.first) return p1.first < p2.first;
    return p1.second->first < p2.second->first;
  }
};

并与您的容器一起使用

std::set< Pair, CompareFirstThroughSecond > queue;  

(我希望我从原始代码中正确解读了您的意图。)

(I hope I deciphered your intent from your original code correctly).

您还可以实现上述 operator()方法作为模板方法,从而使其可用于所有 std: :pair - 以迭代器作为第二成员。它可能不会使mich有意义,因为你的比较是充满异国情调足够。

You can also implement the above operator () method as a template method, thus making it usable with all std::pair-based types with an iterator as a second member. It might not make mich sense though, since your comparison is "exotic" enough.

这篇关于为一对中的一个元素提供小于运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆