我有3个数据结构:队列节点(struct
),队列节点vector
和map
具有作为字符串的键和指向队列节点的指针。它们的定义如下:实现结构向量和指针结构的向量
队列节点:
struct QNode{
int32_t index;
int32_t count;
};
矢量:
vector<QNode> n;
地图:
map<string, QNode*> QueuePointerMap;
每当我创建一个节点时,我将它插入向量中,并将指针存储到刚刚在映射中创建的节点中,并将该键作为唯一字符串存储。我使用下面的代码可以这样做:
n.push_back(QNode());
int insertIndex = n.size();
n[insertIndex-1].index = index-1;
n[insertIndex-1].count = 1;
cout << "***************************\n";
cout << "Insert index: " << insertIndex << "\n";
cout << "n[insertIndex -1].index: " << n[insertIndex -1].index << "\n";
cout << "n[insertIndex -1].count: " << n[insertIndex -1].count << "\n";
cout << "***************************\n";
QueuePointerMap[uniqStr] = &(n[insertIndex-1]);
cout << "Address of N: " << &(n[insertIndex-1]) << "\n\n";
每当我在载体中插入一个节点,它被正确地存储在载体和地图,我插入一个新的节点之后面临的一个问题。每当我在矢量(和地图)中插入一个新值,并且如果我尝试获取以前的值,我会得到与存储的值不同的值。我用我的检索值,下面的代码:
map<string, QNode*>::iterator it1;
it1=QueuePointerMap.find(uniqStr);
if(it1 == QueuePointerMap.end()){
cout << "\n Not Found \n";
}
else{
QNode * n1 = it1->second;
cout << "Value of N1: " << n1 ;
cout << "\t Index: "<< (n1->index) << "\n Count: " << (n1->count) << "\n";
}
我不明白为什么我收到了指数的不同的价值观和计数。我想我在插入时做了一些错误,但我无法弄清楚问题所在。我真的很感激,如果有人帮助我理解并解决这个问题。谢谢。
在将'uniqstr'值设置为'QueuePointerMap'的关键字之前设置的位置/何时? –
我从用户那里得到它,并确保它的独特性。如果不是,则上述操作不会发生。 – TheRookierLearner
尝试使用调试器缓慢地将指针值存储在另一个结构中和/或逐步缓存,并跟踪指针值和QNode struct内部结构。请记住,矢量的[]运算符返回对该位置元素的引用。 [std :: vector :: operator \ [\]](http://en.cppreference.com/w/cpp/container/vector/operator_at) –