簡體   English   中英

訪問 c++ 中列表向量的問題

[英]Problem in accessing vectors of list in c++

我正在嘗試表示一個圖表,其中

邊緣:

struct edge{
char a;
char b;
int weight;
}

我正在嘗試在此數據結構中添加我的圖表:

vector<list<edge*>> graph;

在 AddEdge function 中,我在嘗試在向量的第 i 個索引中添加列表時遇到 memory 訪問沖突

void Graph::addEdge(char start, char end, int weight)
{
    int i = node_number(start); //returns index (e.g 0 if start == 'A')
    int j = node_number(end);
    Edge *s= new Edge (start, end, weight); 
    Edge* e=new Edge (end, start, weight);
    graph[i].push_back(s); //memory violation
    graph[j].push_back(e);
}

現在有人幫我在我的graph中添加邊。 謝謝!

編輯:

我進行了調試,在 push_back() 部分 i 和 j 的值分別為 0 和 1。 調試器返回 abort: memory 違規回溯是:

public:
    _NODISCARD _Ty& operator[](const size_type _Pos)
        {   // subscript mutable sequence
 #if _ITERATOR_DEBUG_LEVEL != 0
        _STL_VERIFY(_Pos < size(), "vector subscript out of range");
 #endif /* _ITERATOR_DEBUG_LEVEL != 0 */

        return (this->_Myfirst()[_Pos]);
        }

問題在於向量的大小,因為下面的初始化分配 size=0

vector<list<edge*>> graph;

我已經通過在推送之前調整圖形向量的大小來修復代碼。 另一種解決方案是通過

vector<list<edge*>> graph(20);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM