问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/2328889/providing-less-than-operator-for-one-element-of-a-pair