2010-06-02 27 views
4

我知道我可以使用下面的基於第二::對成員上:如何創建一組具有的std ::對多數民衆贊成在排序利用綁定

template <typename Pair> 
struct ComparePairThroughSecond : public std::unary_function<Pair, bool> 
{ 
    bool operator()(const Pair& p1, const Pair& p2) const 
    { 
     return p1.second < p2.second; 
    } 
}; 

std::set<std::pair<int, long>, ComparePairThroughSecond> somevar; 

,但不知道是否可以用升壓完成:: bind

+1

什麼問題,你想通過使用boost ::綁定了的std ::設置< >的做法是不合適某種程度上解決解決? – andand 2010-06-02 14:29:09

回答

3

以下情況如何。我使用boost ::函數'擦除'比較器的實際類型。比較器是使用boost:bind自身創建的。

typedef std::pair<int, int> IntPair; 
    typedef boost::function<bool (const IntPair &, const IntPair &)> Comparator; 
    Comparator c = boost::bind(&IntPair::second, _1) < boost::bind(&IntPair::second, _2); 
    std::set<IntPair, Comparator> s(c); 

    s.insert(IntPair(5,6)); 
    s.insert(IntPair(3,4)); 
    s.insert(IntPair(1,2)); 
    BOOST_FOREACH(IntPair const & p, s) 
    { 
    std::cout << p.second; 
    } 
0

問題是,除非您將代碼編寫爲模板或使用C++ 0x功能,否則必須命名boost :: bind表達式的類型。但是這些類型通常具有非常複雜的名稱。

模板參數推導在C++ 98:

template<class Fun> 
void main_main(Fun fun) { 
    set<pair<int,long>,Fun> s (fun); 
    … 
} 

int main() { 
    main_main(…boost::bind(…)…); 
} 

在C汽車和decltype ++ 0x中:

int main() { 
    auto fun = …boost::bind(…)…; 
    set<pair<int,long>,decltype(fun)> s (fun); 
    main_main(boost::bind(…)); 
} 

至於實際綁定的表情,我覺得它是這樣的:

typedef std::pair<int,long> pil; 
boost::bind(&pil::second,_1) < boost::bind(&pil::second,_2) 

(未測試的)

相關問題