将地图值复制到STL中的矢量 [英] Copy map values to vector in STL
问题描述
目前正在通过有效的STL。项目5表明,通常优选对其单个元素对应使用范围成员函数。我目前希望将地图中的所有值(即 - 我不需要键)复制到向量。
Working my way through Effective STL at the moment. Item 5 suggests that it's usually preferable to use range member functions to their single element counterparts. I currently wish to copy all the values in a map (i.e. - I don't need the keys) to a vector.
这是最干净的方法是什么?
What is the cleanest way to do this?
推荐答案
您不能轻易地使用范围,因为从地图得到的迭代器是指std :: pair,其中要用于插入向量的迭代器是指存储在向量中的类型的对象,它是(如果你放弃了键)而不是一个对。
You can't easily use a range here becuase the iterator you get from a map refers to a std::pair, where the iterators you would use to insert into a vector refers to an object of the type stored in the vector, which is (if you are discarding the key) not a pair.
我真的不认为它比明显更清洁:
I really don't think it gets much cleaner than the obvious:
#include <map>
#include <vector>
#include <string>
using namespace std;
int main() {
typedef map <string, int> MapType;
MapType m;
vector <int> v;
// populate map somehow
for( MapType::iterator it = m.begin(); it != m.end(); ++it ) {
v.push_back( it->second );
}
}
这可能会重写为模板函数如果我要使用它不止一次。类似:
which I would probably re-write as a template function if I was going to use it more than once. Something like:
template <typename M, typename V>
void MapToVec( const M & m, V & v ) {
for( typename M::const_iterator it = m.begin(); it != m.end(); ++it ) {
v.push_back( it->second );
}
}
这篇关于将地图值复制到STL中的矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!