简体   繁体   中英

How to store pointer / iterator reference to stl container element in C++?

I am designing a graph class which I want to base on an adjacency list. The class internally has a DataStructure :

std::unordered_map<Node,std::list<??>,NodeHash,NodeEqual> map;

Instead of ?? , I want either pointer to Node element stored in list or some iterator pointing to it.

I am new to C++. How should I go about it?

How do I get pointer to an existing key node from the unordered_map?

Find the element with that key, take the address of the first member of the element.

std::unordered_map<Node,std::list<Node*>,NodeHash,NodeEqual> map;
Node node1;
(void) map[node1];  // add { node1, {} }  to the map
...
auto iter = map.find(node1);
if (iter != map.end())
{
  Node* n = &iter->first;
  Node node2;
  map[node2].push_back(n);
}

Here n is a pointer to the existing key that is equal to node1 .

This works in with ideone ; I don't know if it's portable.

struct M;
typedef std::unordered_map<Node, std::list<M>, NodeHash, NodeEqual> mymap;
struct M { mymap::iterator x; };

Unfortunately, M isn't quite an iterator to mymap , but it's pretty close.

( ideone complains if I try the same trick to make M a wrapper of std::list<mymap::iterator> instead)

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