簡體   English   中英

為一對中的一個元素提供少於運算符

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

什么是最優雅的方式也修復以下代碼:

#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(我知道, 你不應該這樣做。

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

另一個明顯的解決方案是定義小於<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;
  }
};

並將其與容器一起使用

std::set< Pair, CompareFirstThroughSecond > queue;  

(我希望我能正確地從原始代碼中解讀你的意圖)。

您還可以將上面的operator ()方法實現為模板方法,從而使其可以與所有基於std::pair的類型一起使用,並將迭代器作為second成員。 雖然你的比較充分“充滿異國情調”,但它可能並不會讓人感覺到這種感覺。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM