2013-04-24 66 views
1

在下文提到的代碼的「插入」功能,我得到的誤差向量下標越界「:C++向量下標越界只非空載體

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

     } 
    } 
}; 

當傳遞的字符串向量「鄰居」是空的,那麼代碼工作正常,但是當載體有一些元素,那麼它給指定的錯誤

操作系統:Windows 8 IDE:Visual Studio的2013

+1

爲什麼'vector.resize(size + 1)'而不是'vector.push_back(...)'或'vector.emplace_back'? – 2013-04-24 15:57:44

+0

另外,_where_是否收到訂閱錯誤?你有沒有試過在調試器中運行? – 2013-04-24 15:59:25

+2

我還是有點被帶回了'調整(0)'在構造......顯然*以防萬一*標準庫撒了一些隨機向量成'adjList'基於默認構造一些超級祕密RNG? – WhozCraig 2013-04-24 16:01:02

回答

2

除了什麼約阿希姆評論約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。這是,當你已經超出界限。

+0

PD:對不起多次編輯...我想我得到了我打算說正確的這個時候:P – eSedano 2013-04-24 16:13:12

+0

更換||用&&​​解決了這個問題。 – 2013-04-25 09:56:34