在 c++ 中访问列表向量时出现问题

Problem in accessing vectors of list in c++

本文关键字:问题 向量 列表 c++ 访问      更新时间:2023-10-16

>我正在尝试表示一个图形,其中

边缘:

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

我正在尝试在此数据结构中添加我的图形:

vector<list<edge*>> graph;

在AddEdge函数中,我在尝试在向量的第i个索引中添加列表时遇到内存访问冲突

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中添加边缘.谢谢!

编辑:

我进行了调试,i 和 j 的值在 push_back(( 部分分别为 0 和 1。调试器返回中止:内存冲突 回溯为:

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