gpt4 book ai didi

c++ - 由于错误的指针使用导致未处理的异常

转载 作者:行者123 更新时间:2023-11-28 06:17:32 26 4
gpt4 key购买 nike

这是我的第一个问题,对于您可能在我的帖子中发现的最终正式错误,我深表歉意。

我正在为“无向连通加权图”编写一个简单的类,它必须使用基于 vector 的邻接表。

问题是,当我从 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;
}

最佳答案

我注意到代码中有几个错误:

  1. 如果你需要的是邻接表,那么this->adj应该是 vector 的 vector 。目前,它只是一个一维 vector <int,int>对。相反,它应该是:

    std::vector<std::vector<std::shared_ptr<std::pair<int,int>>>>* adj;

  2. 在构造函数中,this->adj应该初始化如下:

    this->adj = new std::vector<std::vector<std::shared_ptr<std::pair<int,int>>>>(V);

  3. 现在,在 addEdge 函数中,您需要首先访问对应于节点 'v' 的 vector ,然后将 (w, weight) 对插入该 vector [注意 即使我们忽略了只有 vector 的错误,逻辑仍然不正确,因为你推的是 (v, weight) 而不是 (w,重量)到那个 vector ]。修改后的 addEdge 函数将是这样的:

    void addEdge(int v, int w, int weight)
    {
    auto adjacencyList = adj->at(v);
    auto sp = std::make_shared<std::pair<int,int>>(std::make_pair(w,weight));
    adjacencyList.push_back(sp);
    }

希望对你有帮助

关于c++ - 由于错误的指针使用导致未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29957264/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com