我们可以很容易地编写一个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());
看来你已经意识到在STL中没有直接的支持(或者可能是提升),为什么不写一个简单的函数模板来为你做这件事?它肯定比'bind'方法或非标准方法更清晰...... – Nim 2011-03-07 09:51:36
@Nim,这可能是一个好主意,但是我总是害怕团队中的每个人都会拿出他自己的版本'littleTidbitMissingFromSpec',所以如果我能找到一些可靠的提升,那会更好。 – 2011-03-07 16:53:27
一个有据可查的utils(或aux)命名空间是你需要的! ;) – Nim 2011-03-07 16:56:33