if (!paths[i].empty()) { std::cout << "path size: " << paths[i].size() << std::endl; QPainterPath path; for (int j = 0; j < paths[i].size() - 1; j++) { Node* current_node = paths[i][j]; Node* next_node = paths[i][j+1]; int x1 = current_node->x; int y1 = current_node->y; int x2 = next_node->x; int y2 = next_node->y; int x_draw1 = x1 * nodeSize + 200 + nodeSize/2; int y_draw1 = y1 * nodeSize + 50 + nodeSize/2; int x_draw2 = x2 * nodeSize + 200 + nodeSize/2; int y_draw2 = y2 * nodeSize + 50 + nodeSize/2; path.moveTo(x_draw1, y_draw1); path.lineTo(x_draw2, y_draw2); } painter.setPen(QPen(Qt::red, 2)); painter.drawPath(path); },一運行就卡死,怎麽修改
时间: 2023-11-27 09:55:00 浏览: 69
这段代码可能会卡死的原因是因为在循环中调用了 `j+1`,当 `j` 为最后一个索引时,`j+1` 会超出 `paths[i]` 的界限,导致程序出现未定义行为。可以修改代码如下:
```c++
if (!paths[i].empty()) {
std::cout << "path size: " << paths[i].size() << std::endl;
QPainterPath path;
for (int j = 0; j < paths[i].size(); j++) { // 修改循环条件
if (j == paths[i].size() - 1) break; // 添加判断语句
Node* current_node = paths[i][j];
Node* next_node = paths[i][j+1];
int x1 = current_node->x;
int y1 = current_node->y;
int x2 = next_node->x;
int y2 = next_node->y;
int x_draw1 = x1 * nodeSize + 200 + nodeSize/2;
int y_draw1 = y1 * nodeSize + 50 + nodeSize/2;
int x_draw2 = x2 * nodeSize + 200 + nodeSize/2;
int y_draw2 = y2 * nodeSize + 50 + nodeSize/2;
path.moveTo(x_draw1, y_draw1);
path.lineTo(x_draw2, y_draw2);
}
painter.setPen(QPen(Qt::red, 2));
painter.drawPath(path);
}
```
修改后,循环从0到`path[i]`的大小,同时在循环中添加了判断语句来避免超出数组范围,这应该可以解决程序卡死的问题。
阅读全文