在下文提到的代碼的「插入」功能,我得到的誤差向量下標越界「: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
爲什麼'vector.resize(size + 1)'而不是'vector.push_back(...)'或'vector.emplace_back'? – 2013-04-24 15:57:44
另外,_where_是否收到訂閱錯誤?你有沒有試過在調試器中運行? – 2013-04-24 15:59:25
我還是有點被帶回了'調整(0)'在構造......顯然*以防萬一*標準庫撒了一些隨機向量成'adjList'基於默認構造一些超級祕密RNG? – WhozCraig 2013-04-24 16:01:02