如何修复C++中矢量的"下标超出范围"错误?
How to fix a "subscript out of range" error for vectors in C++?
我的代码中矢量的错误超出范围。我该怎么做才能阻止错误?我查看了很多论坛。
我已经做了一些基本的试验,看看是否还有其他问题。从 0.再次从头开始编写代码。使用过其他 IDE。
#include <iostream>
#include <vector>
#include "graph.h"
using namespace std;
graph::graph() {
count = 0;
}
void graph::addVertex(const Node node) {
vertices.push_back(node);
count++;
}
void graph::addEdge(const char from, const char to) {
vertices[from].edges.push_back(to);
vertices[to].edges.push_back(from);
}
void graph::print() {
unsigned int i = 0;
while (i < vertices.size()) {
cout << vertices[i].name << "->";
if (vertices[i].edges.size() > 0)
for (unsigned int j = 0; j < vertices[i].edges.size(); j++)
cout << vertices[i].edges[j];
cout << endl;
i++;
}
结果总是将我带到矢量文件的第 1733 行,我不确定修复错误后是否会出现更多错误。
感谢您的回复,尤其是@user4581301,我搞砸了它,输出按照这个替代 addEdge 函数的预期出现。
void graph::addEdge(const char from, const char to) {
if (vertices.size() == 0)
return;
for (int i = 0; i < vertices.size(); i++) {
if (vertices[i].name == from)
vertices[i].edges.push_back(to);
if (vertices[i].name == to)
vertices[i].edges.push_back(from);
}
}
相关文章:
- 尝试通过多个向量访问变量时,向量下标超出范围
- 矢量下标超出SFML游戏中的范围
- 运行时错误:矢量下标超出范围:正在检查空集
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 编译期间矢量下标超出范围
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 对矢量来说是全新的.矢量下标超出范围
- C++十进制到十六进制(字符串下标超出范围)
- 创建结构体向量,表达式:向量下标超出范围
- 读取矢量时矢量下标超出范围
- 断言失败错误,C++中的矢量下标超出范围问题
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 表达式:矢量下标超出范围
- 矢量下标超出范围,带有嵌套的 for 循环
- 向量下标超出向量向量的范围
- gcc8.2如何启用警告:数组下标在数组范围之上[-warray-bounds]
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- std::vector<std::vector<int>>:调试断言失败。C++矢量下标超出范围保留内存
- 重命名两个目录中的文件名,如果它们之间的某些字符匹配 - 矢量下标超出范围
- C++超出下标范围