2011-03-07 57 views
10

是否有返回p->firstp->second和內置函數對象,這樣我可以愉快地寫C++函數對象返回`P-> first`和`對 - >秒'

transform(m.begin(),m.end(),back_inserter(keys),get_first); 
transform(m.begin(),m.end(),back_inserter(vals),get_second); 

基於STL-溶液是最好的,boost解決方案是次佳。我知道boost::lambda,我不想開始使用它。

+1

看來你已經意識到在STL中沒有直接的支持(或者可能是提升),爲什麼不寫一個簡單的函數模板來爲你做這件事?它肯定比'bind'方法或非標準方法更清晰...... – Nim 2011-03-07 09:51:36

+1

@Nim,這可能是一個好主意,但是我總是害怕團隊中的每個人都會拿出他自己的版本'littleTidbitMissingFromSpec',所以如果我能找到一些可靠的提升,那會更好。 – 2011-03-07 16:53:27

+0

一個有據可查的utils(或aux)命名空間是你需要的! ;) – Nim 2011-03-07 16:56:33

回答

9

g++SGI的非標準擴展名被稱爲select1stselect2nd。所以STL可能沒有這個功能。

Boost的綁定也可以做到這一點,給它一個指向正確的成員函數

boost::bind(&std::map<string,string>::value_type::second,_1) 
2

如果你可以使用C++ 0x中,因爲G ++ 4.5您可以使用真正的lambda表達式,或者您可以使用新的與std :: pairs完全兼容的元組庫。然後你可以使用std :: get < 0>來獲得第一個,std :: get < 1>。

如果你綁定到C++ 98,你可以使用std :: tr1 :: tuple而不是std :: pair,就像在TR1中get不能和std :: pair一樣。

你也可以使用TR1(tr1/functional)的綁定,就像Elazar描述的那樣。

4

我們可以很容易地編寫一個select1st和select2nd:

struct select1st 
{ 
    template< typename K, typename V > 
    const K& operator()(std::pair<K,V> const& p) const 
    { 
     return p.first; 
    } 
}; 

struct select2nd 
{ 
    template< typename K, typename V > 
    const V& operator()(std::pair<K,V> const& p) const 
    { 
     return p.second; 
    } 
}; 

這裏是一個另類,其實更靈活的版本:

struct select1st 
{ 
    template< typename P > 
    typename P::first_type const& operator()(P const& p) const 
    { 
     return p.first; 
    } 
}; 

struct select2nd 
{ 
    template< typename P > 
    typename P::second_type const& operator()(P const& p) const 
    { 
     return p.second; 
    } 
}; 

隨後:

transform(m.begin(),m.end(),back_inserter(keys), select1st()); 
transform(m.begin(),m.end(),back_inserter(vals), select2nd());