map<T,Z> m= ...;
vector<T> v;
v.reserve(m.size);
for(map<T,Z>::iterator it=m.begin();it!=m.end();++it)
{
v.push_back(it->first);
}
有没有更好的1行版本使用一些STL功能?
编辑:不用c 11!
解决方法
便携性:
struct SelectKey {
template <typename F,typename S>
F operator()(const std::pair<const F,S> &x) const { return x.first; }
};
std::transform(m.cbegin(),m.cend(),std::back_inserter(v),SelectKey());
我认为STL的一些实现有一个名为select1st的非标准扩展,这相当于这里显示的SelectKey.正如K-Ballo在评论中指出的那样,还有一个TR1版本.我喜欢明确的版本,因为它更容易看到发生了什么.
由于不需要状态,您可以通过使用实际的功能而不是函子来减少样板,
template <typename F,typename S>
F SelectKey()(const std::pair<const F,S> &x) { return x.first; }
std::transform(m.cbegin(),SelectKey);
如果您可以使用C 11,则可以使用lambda来保持选择代码与使用的位置相近:
std::transform(m.cbegin(),[](const std::pair<const F,S> &x) { return x.first; });
或甚至基于范围的for-loop,这可能是最优雅和可读性:
for(const auto &x : m) {
v.push_back(x.first);
}