c++中的vector下标超出了非空vector的范围

C++ vector subscript out of range only with non-empty vector

本文关键字:vector 范围 中的 下标 c++      更新时间:2023-10-16

在下面提到的代码的"insert"函数中,我得到的错误向量下标超出了范围":

// this acts as the vertex of graph
typedef struct node
{
    string name;    // stores the unique name of the vertex
    int value;      // stores the integer data saved in the vertex
} node;
class graph
{
private:
    // 2D vector to store the adjencey list of the graph
    vector< vector<node> > adjList;
public:
    graph()
    {
        adjList.resize(0);
    }
    // function to insert a vertex in graph.
    //  'nName' : unique name of vertex;
    //  'nValue': int data stored in vertex;
    //  'neighbours': string vector containing names of all neighbours
    void insert(string nName, int nValue, vector<string> neighbours)
    {
        int i= adjList.size();
        adjList.resize(i + 1);
        adjList[i].resize( neighbours.size() + 1);
        adjList[i][0].name = nName;
        adjList[i][0].value = nValue;
        string temp;
        for(int nTrav=0, lTrav=1, size=neighbours.size(); nTrav<size; ++nTrav, ++lTrav)
        {
            temp=neighbours[nTrav];
            int j=0;
            for(; j<adjList.size() || adjList[j][0].name != temp; ++j);
            if(j==adjList.size())
            {
                cout << "nName not present. Element not inserted";
                return;
            }
            adjList[i][lTrav].name = adjList[j][0].name;
            adjList[i][lTrav].value = adjList[j][0].value;
        }
    }
};

当传入的字符串vector 'neighbour'为空时,代码正常工作,但当vector包含某些元素时,则给出指定的错误。

操作系统:Windows 8IDE: Visual Studio 2013

除了Joachim对vector.push_back(...)的评论之外,您应该将第二个循环更改为:

for(; j<adjList.size() && adjList[j][0].name != temp; ++j)

用AND代替OR。在评估其内容之前,您必须确保满足j<adjList.size()条件。否则,由于延迟计算,当j<adjList.size()返回false时,您实际上只计算adjList[j][0].name != temp