Copy map values to vector in STL(将地图值复制到 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.
最干净的方法是什么?
推荐答案
在这里你不能轻易地使用范围,因为你从 map 中得到的迭代器指的是一个 std::pair,你将用来插入的迭代器into a vector 是指存储在向量中的类型的对象,它是(如果您丢弃键)不是一对.
You can't easily use a range here because 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 中的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将地图值复制到 STL 中的向量
基础教程推荐
- 使用scanf()读取字符串 1970-01-01
- C++定义类对象 1970-01-01
- C语言访问数组元素 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- C++ #define 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- 初始化变量和赋值运算符 1970-01-01
- C++按值调用 1970-01-01
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- C++输入/输出运算符重载 1970-01-01