如何在C ++中将值从向量转换为地图? [英] How do I convert values from a vector to a map in c++?

查看:63
本文介绍了如何在C ++中将值从向量转换为地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情.有一个stl算法可以轻松做到这一点吗?

I want to do something like this. Is there a stl algorithm that does this easily?

 for each(auto aValue in aVector)
                {
                aMap[aValue] = 1;
                }

推荐答案

如果有向量对,则其中的第一项将是地图的键,第二项将是与之关联的值该键,您只需使用插入迭代器将数据复制到地图即可:

If you have a vector of pairs, where the first item in the pair will be the key for the map, and the second item will be the value associated with that key, you can just copy the data to the map with an insert iterator:

std::vector<std::pair<std::string, int> > values {   
    {"Jerry", 1},
    { "Jim", 2},
    { "Bill", 3} };

std::map<std::string, int> mapped_values;

std::copy(values.begin(), values.end(), 
          std::inserter(mapped_values, mapped_values.begin()));

或者,您可以从矢量初始化地图:

or, you could initialize the map from the vector:

std::map<std::string, int> m2((values.begin()), values.end());

这篇关于如何在C ++中将值从向量转换为地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆