简体   繁体   English

如何在C ++中存储指向stl容器元素的指针/迭代器引用?

[英]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 : 该类内部有一个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. ,我想要指向存储在列表中的Node元素的指针或指向它的一些迭代器。

I am new to C++. 我是C ++的新手。 How should I go about it? 我该怎么办呢?

How do I get pointer to an existing key node from the unordered_map? 如何从unordered_map获取指向现有关键节点的指针?

Find the element with that key, take the address of the first member of the element. 找到具有该键的元素,获取元素的first成员的地址。

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 . 这里n是指向等于node1的现有键的指针。

This works in with ideone ; 这适用于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. 不幸的是, M是不是给迭代器mymap ,但它是相当接近。

( ideone complains if I try the same trick to make M a wrapper of std::list<mymap::iterator> instead) (如果我尝试使用相同的技巧使M成为std::list<mymap::iterator>的包装,那么ideone抱怨)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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