![](/img/trans.png)
[英]Short function to insert into a std::map<int, std::vector<int>>
[英]Insert std::map into std::vector directly
对不起,如果问题非常简单。
我有一张地图矢量:
typedef map<char, int> edges;
typedef vector<edges> nodes;
nodes n;
现在让我们说我想推动玩具优势。 我尝试了不同的东西,我的工作是什么
edges e; //declare an edge
e['c'] = 1; //initialize it
n.push_back(e); //push it to the vector
如何在不必声明变量并初始化它的情况下,只需按下边('c'和2)的值对?
就像是:
n.push_back(edges('c',2));
但编译器给出了错误
error: no matching function for call to ‘std::map<char, int>::map(char, int)’
您可以列出初始化:
nodes vec {
{ {'a', 12}, {'b', 32} },
{ {'c', 77} },
};
vec.push_back(
{ {'d', 88}, {'e', 99} }
);
在您的解决方案中,您将map
添加到矢量而不是成对。 方法应迭代每个元素以将其置于向量中。 因此,您可以使用n[0]['c']
等访问元素。
我想,使用for_each
和一个带有传递向量引用的lambda表达式来创建一个单行解决方案来将对添加到向量中。
#include <algorithm>
typedef map<char, int> edges;
//change this to take pair
typedef vector<pair<char, int>> nodes;
nodes n;
edges e; //declare an edge
//map elements are pairs
for_each(e.begin(), e.end(), [&n](pair<char, int> p) { n.push_back(p); });
我希望这能为您解释一个解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.