Insert std::map into std::vector directly

送分小仙女□ 提交于 2019-12-06 02:18:13

You can list initialization:

nodes vec {
    { {'a', 12}, {'b', 32} },
    { {'c', 77} },
};

vec.push_back(
        { {'d', 88}, {'e', 99} }
        );

Use an extended initializer list, like this:

n.push_back({ {'c', 2} });

Live demo

Requires C++11, or later.

In your solution, you add map to vector instead of pairs. A method should iterate over each element to place it in vector. Therefore you can access to element with n[0]['c'] etc.

I thought, using for_each and a lambda expression with passing vector reference to create a one line solution to add pairs into vector.

#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); });

I hope this explains a solution for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!