C++函数对象返回`p-> first`和`p-> second`

Ela*_*ich 10 c++ boost stl

是否有一个返回内建函数对象p->firstp->second,让我可以高兴地写

transform(m.begin(),m.end(),back_inserter(keys),get_first);
transform(m.begin(),m.end(),back_inserter(vals),get_second);
Run Code Online (Sandbox Code Playgroud)

基于STL的解决方案是最好的,boost解决方案是第二好的.

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

Ela*_*ich 9

有非标准扩展g++SGI调用select1stselect2nd.因此STL中可能没有任何内容.

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

boost::bind(&std::map<string,string>::value_type::second,_1)
Run Code Online (Sandbox Code Playgroud)


Cas*_*Cow 5

我们可以轻松编写 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;
   }
};
Run Code Online (Sandbox Code Playgroud)

这是一个替代的,实际上更灵活的版本:

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;
   }
};
Run Code Online (Sandbox Code Playgroud)

随后:

transform(m.begin(),m.end(),back_inserter(keys), select1st());
transform(m.begin(),m.end(),back_inserter(vals), select2nd());
Run Code Online (Sandbox Code Playgroud)