我试图将deque的迭代器存储在向量中,并希望将它们保存在向量中,即使我已经删除或插入了deque中的某些元素。这可能吗?
我有以下代码:
typedef struct {
int id;
int seedId;
double similarity;
} NODE_SEED_SIM;
typedef std::deque<NODE_SEED_SIM> NodesQueue;
typedef std::deque<NODE_SEED_SIM>::iterator ITRTR;
typedef std::vector<const ITRTR> PointerVec;
void growSegments (CSG_PointCloud *pResult, IntMatrix *WdIndices, NodesQueue *NodesList, IntMatrix *Segments) {
ITRTR nodeslistStart = (*NodesList).begin();
int pointCount = (*WdIndices).size();
int nodeslistSize = (*NodesList).size();
IntVector book(pointCount);
PointerVec pointerList (pointCount); // Vector of ITRTRs
for (int i = 0; i < nodeslistSize; i++) {
book [ (*NodesList)[i].id ] = 1;
pointerList [ (*NodesList)[i].id ] = nodeslistStart + i; // REF: 2
}
while (nodeslistSize > 0) {
int i = 0;
int returnCode = 0;
int nodeId = (*NodesList)[i].id;
int seedId = (*NodesList)[i].seedId;
int n_nbrOfNode = (*WdIndices)[ nodeId ].size();
(*Segments)[ seedId ].push_back ( nodeId );
(*NodesList).erase ( (*NodesList).begin() ); // REF: 3; This erase DOES NOT mess the pointerList
nodeslistSize --;
Point node;
/*
GET ATTRIBUTES OF NODE
*/
for (int j = 0; j < n_nbrOfNode; j++) {
int nborId = (*WdIndices)[nodeId][j];
if (nborId == seedId)
continue;
Point neighbor;
/*
GET ATTRIBUTES OF NEIGHBOUR
*/
double node_nbor_sim = computeSimilarity (neighbor, node);
if (book[nborId] == 1) {
ITRTR curr_node = pointerList[nborId]; // REF: 1
if ( curr_node -> similarity < node_nbor_sim) {
curr_node -> similarity = node_nbor_sim;
NODE_SEED_SIM temp = *curr_node;
(*NodesList).erase (curr_node); // REF: 4; This erase completely messes up the pointerList
returnCode = insertSortNodesList (&temp, NodesList, -1);
}
}
}
}
}
NodesList中的节点在其中包含全局ID。但是它们存储在NodesList中,而不是根据这个全局ID,而是按照它们的相似性#34;的降序排列。所以后来当我想从NodesList获取对应于全局ID(代码中的nborID)[REF:1]的节点时,我通过&#34; pointerList&#34;我以前存储过deque的迭代器但是根据节点的全局ID [REF:2]。我的pointerList在第一个擦除命令[REF:3]之后保持为真,但在下一次擦除[REF:4]时被搞砸了。
这里有什么问题? 感谢
答案 0 :(得分:2)
我试图将deque的迭代器存储在向量中,并希望将它们保存在向量中,即使我已经删除或插入了deque中的某些元素。这可能吗?
从它所说的documentation开始
对不起,我在这里将其作为图片发布,但格式化过于繁琐,无法在标记中复制!
所以简短的回答是:不!我担心你不能安全地存储指向存储在std::deque
中的某些元素的迭代器,而它在其他地方已经改变了
其他一些相关的Q&amp; A:
答案 1 :(得分:-1)
如果你想创建一个vector
iterators
,那么这就是你想要做的:
#include<iostream>
#include <deque>
#include <vector>
using namespace std;
int main()
{
deque<int> dq { 1, 2, 3, 4, 5, 6, 7, 8 };
deque<int>::iterator it;
vector<deque<int>::iterator> vit;
for (it = dq.begin(); it != dq.end(); it++)
{
vit.push_back(it);
cout << *it;
}
//note that `it` is a pointer so if you modify the `block` it points in your deque then the value will change.
//If you delete it then you will have a segmenant fault.
//--- Don't Do: while (!dq.empty()) { dq.pop_back(); } ---//
for (size_t i = 0; i < vit.size(); i++)
{
cout << *vit[i];
}
system("pause");
return 0;
}
但是,如果要在更改/删除iterator
之后保留该iterator
的值,您可能需要创建每个iterator
的副本并存储副本而不是实际的{{1}} 1}}