是否有一个返回内建函数对象p->first和p->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,我不想开始使用它.
有非标准扩展g++和SGI调用select1st和select2nd.因此STL中可能没有任何内容.
Boost的绑定也可以这样做,给它一个指向正确成员函数的指针
boost::bind(&std::map<string,string>::value_type::second,_1)
Run Code Online (Sandbox Code Playgroud)
我们可以轻松编写 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)