如何修复C++中矢量的"下标超出范围"错误?

How to fix a "subscript out of range" error for vectors in C++?

本文关键字:下标 范围 错误 C++ 何修复      更新时间:2023-10-16

我的代码中矢量的错误超出范围。我该怎么做才能阻止错误?我查看了很多论坛。

我已经做了一些基本的试验,看看是否还有其他问题。从 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);
    }
}