问题描述
我需要使用一个向量来实现我的地图。我的地图布局如下:
map<strong,double> mapName;
我需要转换为向量,以便可以对元素进行线性搜索。
提前感谢您抽出时间。
推荐答案
可以使用向量的范围构造函数轻松转换为向量,如下所示:
map<string,double> item_map;
// ... populate item map ...
// copy elements to a vector.
vector< pair<string,double> > item_vector(item_map.begin(), item_map.end());
但是,如果您只需要执行线性搜索,则不需要复制元素。只需迭代这些项,如下所示:
typedef map<string,double>::iterator iterator;
iterator current = item_map.begin();
const iterator end = item_map.end();
for (; current != end; ++current) {
// current->first is the 'string' part.
// current->second is the 'double' part.
}