简体   繁体   中英

Inserting a key value in a map where value of map is a vector pair

I've a hard time to figure out how to insert an element in this following type of map. Given:

std::map<Node*, std::vector<pair<Edge*, Node*> > > adjacencyMap;

,where Node and Edge are structs. I want to create a graph and each connection between two nodes should be stored in this map. Each node could have more than one connection to another node. The main idea is that for each node there could be a list of pairs of edges and nodes, eg

node1 and node2 are connected through an edge12
node1 and node3 are connected through an edge13

The adjacencyMap should like

node1 -> [(edge12, node2), (edge13, node3)]
node2 -> [(edge12, node1)]
node3 -> [(edge13, node1)]

I know how to insert an element like (node1, pair(edge12,node2)) but I don't know how to insert, if (node1, pair(edge12,node2)) is already an element, (node1, pair(edge13, node3)) sucht that

node1 -> [(edge12, node2), (edge13, node3)].

How can I realize my intention?

Thanks in advance!

I'm assuming that memory management for Node and Edge is somewhere else since storing raw pointers implies that nobody will take care of their management.

operator[] of std::unordered_map already constructs a default value if it was not present so acually it's enough to just push them:

map[node1].emplace_back(edge13, node2);
map[node1].emplace_back(edge13, node3);

You might do:

adjacencyMap[node1] = {{edge12, node2}, {edge13, node3}};
adjacencyMap[node2] = {{edge12, node1}};
adjacencyMap[node3] = {{edge13, node1}};

or even:

std::map<Node*, std::vector<std::pair<Edge*, Node*>>> adjacencyMap =
{
    {node1, {{edge12, node2}, {edge13, node3}}},
    {node2, {{edge12, node1}}},
    {node3, {{edge13, node1}}}
};

To add nodes, you might do:

// use alias to avoid several look-up
auto& v1 = adjacencyMap[node1]; // auto is std::vector<std::pair<Edge*, Node*>>>
// Then do job on the vector:
v1.emplace_back(edge12, node2);
v1.emplace_back(edge13, node3);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM