这是我在这里的第一个问题,因此对于您在我的帖子中可能发现的最终形式错误,我深表歉意。
我正在为“无向连接加权图”编写一个简单的类,它必须使用基于向量的邻接列表。
问题是,当我从 Eclipse 运行程序时,MS Windows 说它“停止工作”,调试后我收到“0x00AE251A 处的未处理异常......访问冲突写入位置......”消息。环顾四周,我发现这个问题可能是由于缺少指针破坏或指针初始化(?)引起的。我从标准指针切换到 shared_ptr 来解决这个问题,但错误是一样的......
有人可以启发我吗?我几乎浪费了一整天的时间来寻找原因,但没有成功。
class UndirectedGraph
{
private:
int V;
std::vector<std::shared_ptr<std::pair<int,int>>>* adj;
public:
UndirectedGraph(int V)
{
this->V = V;
this->adj = new std::vector<std::shared_ptr<std::pair<int,int>>>;
}
void addEdge(int v, int w, int weight)
{
auto sp = std::make_shared<std::pair<int,int>>(std::make_pair(v,weight));
adj[v].push_back(sp);
}
int main()
{
UndirectedGraph G1(7);//Ok
G1.addEdge(0,1,9);//Ok
G1.addEdge(1,2,5);//Ok
G1.addEdge(2,0,8);//EXCEPTION RAISED HERE (if line is commented all run fine)
return 0;
}