【问题标题】:Implementing vector of structs and map having pointers to the struct实现结构的向量和具有指向该结构的指针的映射
【发布时间】:2014-03-25 10:18:24
【问题描述】:

我有 3 个数据结构:一个队列节点 (struct)、一个队列节点的 vector 和一个 map,其键为字符串和指向队列节点的指针。它们的定义如下:


队列节点:

struct QNode{
    int32_t index;
    int32_t count;
};

矢量:

vector<QNode> n;

地图:

map<string, QNode*> QueuePointerMap;

每当我创建一个节点时,我都会将它插入到向量中,并将指向刚刚在 map 中创建的节点的指针存储为唯一的字符串。我使用以下代码:

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 的键之前,它在何处/何时设置?
  • 我从用户那里得到它,并确保它是独一无二的。如果不是,则上述操作不会发生。
  • 尝试将指针值临时存储在另一个结构中和/或使用调试器慢慢进行并跟踪指针值和 QNode 结构内部。请记住,向量的[] 运算符返回对该位置元素的引用。 std::vector::operator[]

标签: c++ pointers stl


【解决方案1】:

每当您在向量中插入新值时,向量可能会或可能不会重新组织其内部结构(将对象重新定位到不同的内存位置等),因此您从向量元素获得的旧指针可能会或可能不会无效...

http://www.cplusplus.com/reference/vector/vector/push_back/ 说:

如果发生重新分配,所有与容器相关的迭代器、指针和引用都将失效。

【讨论】:

  • 你可以映射到索引... map QueueIndexMap;
  • @TheRookierLearner,如果您事先知道要放入向量中的值的数量 (N),则可以致电 vector.reserve(N)。然后在超过该数字之前不会调整大小。
  • 映射到向量索引而不是元素指针可能也更容易维护。
  • @user2079303 - 这是一条救命稻草评论。 :)
猜你喜欢
  • 2012-02-07
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多