简体   繁体   English

存储和管理std :: list :: iterator

[英]Storing and managing std::list::iterator

Context: I am implementing the Push-Relable Algorithm for MaxFlow in a network and want to keep track of labels of all nodes, for each possible label ( 2*V-1 many) I want to have a doubly-linked list containing the nodes with that label. 上下文:我正在网络中实现针对MaxFlow的Push-Relable算法,并希望跟踪所有节点的标签,对于每个可能的标签(很多2*V-1 ),我希望有一个包含节点的双向链接列表带有那个标签。

So I have a vector where each entry is a list. 所以我有一个向量,其中每个条目都是一个列表。 Now I need to delete an element from one list and move it into another list in another vector-entry. 现在,我需要从一个列表中删除一个元素,然后将其移动到另一个矢量输入中的另一个列表中。 In order to do so, I use an vector (wich size is equal to the number of elements) where each entry is an interator, so I always know the position of each element. 为了做到这一点,我使用一个向量(其大小等于元素的数量),其中每个条目都是一个插入符,所以我总是知道每个元素的位置。 Before implementing it on a bigger scale I wanted to try whether it works at all. 在大规模实施之前,我想尝试一下它是否完全有效。 So I create the two vectors, add one element into a list, store the iterator in the other vector and try to delete that element again. 因此,我创建了两个向量,将一个元素添加到列表中,将迭代器存储在另一个向量中,然后尝试再次删除该元素。 But the std::vector::erase() method always gets me SegFaults. 但是std::vector::erase()方法总是让我遇到SegFaults。 Did I miss something? 我错过了什么?

int V=50; 
int i=0, v=42;

vector<list<int> > B(2*V-1);
vector<list<int>::iterator> itstorage(V) ;

B[i].push_back(v);
itstorage[v]=B[i].end();

B[i].erase(itstorage[v]);

B[i].end() does not refer to the last item you pushed, it is one past the item you pushed. B[i].end()不引用您推送的最后一个项目,而是您推送的项目的最后一个。

What you want is: 您想要的是:

std::list<int>::iterator p = B[i].end();
--p;

Alternatively, instead of using push_back, you could use the insert member function which returns an iterator to the newly inserted item. 或者,可以使用insert成员函数来代替push_back,该函数将迭代器返回到新插入的项目。

itstorage[v] = B[i].insert(B[i].end(), v);

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

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