【发布时间】:2017-03-06 18:00:11
【问题描述】:
我有一小段代码,其中包含一个用于二维顶点的类 (Vector2) 向量和一个模板类 DynamicLine 的向量,该向量以 Vector2 类型对象为参数。
std::vector<Vector2> m_coords;
std::vector<DynamicLine<Vector2>> m_lines;
Vector2 *lineVec = NULL;
bool draw = true;
case DrawingWidgetState::ADD_VERTEX_SELECTED:{
for(auto it = m_coords.begin(); it != m_coords.end(); it++)
if(it->distanceFrom(Vector2(event->x(), event->y())) < 20 && !m_coords.empty()){
draw = false;
break;
}
if(draw){
if(event->x() < m_mainWindow->width() - 10 && event->x() >= 10
&& event->y() < m_mainWindow->height() && event->y() >= 10) {
m_coords.push_back(Vector2(event->x(), event->y()));
update();
}
}
break;
}
case DrawingWidgetState::ADD_LINE_SELECTED:{
for(auto it = m_coords.begin(); it != m_coords.end(); it++)
if(it->distanceFrom(Vector2(event->x(), event->y())) < 10){
if(!i){
lineVec = &(*it);
i++;
}
else{
m_lines.push_back(DynamicLine<Vector2>(lineVec, &(*it)));
i = 0;
}
update();
break;
}
break;
}
问题是下一个。例如,如果我添加两个顶点和它们之间的一条线,那么一切正常。但是,如果我现在添加另一个顶点(m_coords.push_back(Vector2(event->x(), event->y()));) 则 m_lines 向量中的线 dissaperas 和值将更改为非常随机的大数字。我读了一些关于指针失效的东西。如果您将新值推送到向量,那么某些值最终会被扩展。我还使用 vector::reserve 解决了我的问题,但既然我确定我做的不对,谁能解释我应该如何使用 vector::reserve 以及为什么我需要这样做?
【问题讨论】:
-
1) 修正缩进。 2) 创建minimal reproducible example。 3)尝试使用调试器,单步执行您的代码,同时检查每一步的变量值。按此顺序。
标签: c++ pointers memory vector