0

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

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

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

1 回答 1

1

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

  1. 如果您需要的是邻接列表,那么this->adj应该是向量的向量。目前,它只是一个一维向量<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' 对应的向量,然后,您需要将对 (w, weight) 推送到该向量中 [注意,即使我们忽略存在的错误只有向量,逻辑仍然不正确,因为您将(v,权重)而不是(w,权重)推入该向量]。修改后的 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);
    }
    

希望这可以帮助你

于 2015-04-30T02:09:20.917 回答