Kos*_*lek 6 c++ stl operators operator-keyword
什么是最优雅的方式也修复以下代码:
#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
};
Run Code Online (Sandbox Code Playgroud)
修复它的一种方法是将less <to namespace命名为std(我知道, 你不应该这样做.)
namespace std {
bool operator< ( area_t const& a, area_t const& b ) {
return( a->first < b->first );
};
};
Run Code Online (Sandbox Code Playgroud)
另一个明显的解决方案是定义小于<for pair <int,area_t>,但我想避免这种情况,并且只能为未定义的对中的一个元素定义运算符.
当您实现一个实现某种特定和/或相当奇特的比较方法的比较器时,最好使用命名函数或函数对象而不是operator <为此目的而劫持.我要说比较一个std::pair对象的自然方法是使用词典比较.由于您的比较不是词典,因此接管operator <可能不是一个好主意.更好地实现比较器类
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;
}
};
Run Code Online (Sandbox Code Playgroud)
并将其与容器一起使用
std::set< Pair, CompareFirstThroughSecond > queue;
Run Code Online (Sandbox Code Playgroud)
(我希望我能正确地从原始代码中解读你的意图).
您还可以将上述operator ()方法实现为模板方法,从而使其可以与std::pair迭代器作为second成员的所有类型一起使用.虽然你的比较充分"充满异国情调",但它可能并不会让人感觉到这种感觉.