C++ function object to return `p->first` and `p->second`

后端 未结 3 1194
北恋
北恋 2021-01-17 19:02

Is there a builtin function object that returns p->first and p->second, so that I can happily write

transform(m.begin(),m.end         


        
3条回答
  •  一整个雨季
    2021-01-17 19:13

    We can easily write a select1st and select2nd:

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

    Here is an alternative, actually more flexible version:

    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;
       }
    };
    

    subsequently:

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

提交回复
热议问题