1

在下面提到的代码的“插入”函数中,我得到的错误向量下标超出范围“:

// 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;

        }
    }
};

当传递的字符串向量'neighbour'为空时,代码可以正常工作,但是当向量有一些元素时,它会给出指定的错误。

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

4

1 回答 1

2

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

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

将 OR 替换为 AND。在评估其内容之前,您必须确保j<adjList.size()满足条件。否则,由于惰性评估,您实际上只会adjList[j][0].name != tempj<adjList.size()返回 false 时进行评估。这是,当你已经超出界限时。

于 2013-04-24T16:08:13.150 回答