首页 > 解决方案 > 向对向量添加元素会引发错误:分割违规信号

问题描述

我有以下课程:

namespace detail {

    
    class AdjacencyListGraphBase {
    protected:
        // these are the edges in the graph - each outbound edge comes with a weight
        std::vector<std::vector<std::pair<uint32_t, float>>> edges;

        virtual size_t get_num_nodes() const = 0; // call the derived class to get the number of nodes

    public:
        void add_edge(uint32_t from, uint32_t to, float weight=1.0f);
        void remove_edge(uint32_t from, uint32_t to);
        std::optional<float> get_edge(uint32_t from, uint32_t to) const;

        const std::vector<std::pair<uint32_t, float>>& get_edges_starting_at(uint32_t node) const;
    };
}

我想添加一个具有以下功能的元素:

    void detail::AdjacencyListGraphBase::add_edge(uint32_t from, uint32_t to, float weight)
{
    if(!(edges[from][to].first==to)){
        edges[from][to].first = to;
        edges[from][to].second = weight;
    }
}

但是当我调用此函数时,出现以下错误:SIGSEGV - Segmentation violation signal。我不知道我在这里做错了什么。我是否必须调整矢量边缘的大小?还是有什么我看不到的东西丢失了?提前致谢!

标签: c++

解决方案


推荐阅读