简体   繁体   English

为一对中的一个元素提供少于运算符

[英]Providing less than operator for one element of a pair

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

One way to fix it is moving the definition of less< to namespace std (I know, you are not supposed to do it. ) 修复它的一种方法是将less <to namespace命名为std(我知道, 你不应该这样做。

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

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. 另一个明显的解决方案是定义小于<for pair <int,area_t>,但我想避免这种情况,并且只能为未定义的对中的一个元素定义运算符。

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. 当您实现一个实现某种特定和/或相当奇特的比较方法的比较器时,最好使用命名函数或函数对象而不是为此目的劫持operator < I'd say that the natural way to compare a std::pair object would be to use lexicographical comparison. 我要说比较std::pair对象的自然方法是使用词典比较。 Since your comparison is not lexicographical, taking over operator < might not be a good idea. 由于您的比较不是词典,因此接管operator <可能不是一个好主意。 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;
  }
};

and use it with your container 并将其与容器一起使用

std::set< Pair, CompareFirstThroughSecond > queue;  

(I hope I deciphered your intent from your original code correctly). (我希望我能正确地从原始代码中解读你的意图)。

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. 您还可以将上面的operator ()方法实现为模板方法,从而使其可以与所有基于std::pair的类型一起使用,并将迭代器作为second成员。 It might not make mich sense though, since your comparison is "exotic" enough. 虽然你的比较充分“充满异国情调”,但它可能并不会让人感觉到这种感觉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM