简体   繁体   中英

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. )

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.

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

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. It might not make mich sense though, since your comparison is "exotic" enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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