【问题标题】:C++ function object to return `p->first` and `p->second`C++ 函数对象返回 `p->first` 和 `p->second`
【发布时间】:2011-03-07 09:38:21
【问题描述】:

有没有返回p->firstp->second的内置函数对象,这样我就可以愉快的写了

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

基于 STL 的解决方案最好,boost 解决方案次之。

是的,我知道boost::lambda,我不想开始使用它。

【问题讨论】:

  • 您似乎已经意识到STL(或可能是boost)中不存在直接支持,为什么不编写一个简单的函数模板来为您做这件事呢?它肯定比bind 方法或非标准方法更清晰......
  • @Nim,这可能是个好主意,但我总是担心团队中的每个人都会想出自己版本的littleTidbitMissingFromSpec,所以如果我能找到一些可靠的提升,会更好。
  • 您需要一个有据可查的 utils(或 aux)命名空间! ;)

标签: c++ boost stl


【解决方案1】:

g++SGI 的非标准扩展名为 select1stselect2nd。因此,STL 中可能没有任何内容。

Boost 的绑定也可以做到这一点,给它一个指向正确成员函数的指针

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

【讨论】:

    【解决方案2】:

    我们可以很容易地写一个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());
    

    【讨论】:

      【解决方案3】:

      如果您可以使用 C++0x,您可以使用自 G++ 4.5 以来的真正 lambda,也可以使用与 std::pairs 完全兼容的新元组库。然后你可以使用 std::get 作为第一和 std::get 作为第二。

      如果你绑定到 C++98,你可以使用 std::tr1::tuple 代替 std::pair,因为 TR1 get 不适用于 std::pair。

      您也可以像 Elazar 所描述的那样使用 TR1 (tr1/functional) 中的绑定。

      【讨论】:

        猜你喜欢
        • 2020-09-22
        • 2016-06-16
        • 1970-01-01
        • 1970-01-01
        • 2014-12-18
        • 2022-01-03
        • 2021-10-24
        • 2013-05-31
        • 2021-08-30
        相关资源
        最近更新 更多