c ++错误:分段错误(核心转储)

时间:2017-05-10 05:59:31

标签: c++ graph

我已为图表编写了此代码。此代码已成功编译,但在运行时显示Segmentation fault (core dumped)

此代码使用printGraph函数在图表旁边打印。如何解决此错误?

    class graph{
    public:
        std::vector< std::vector<int> > list;
        int n;
        graph(int n){
            this->n=n;
            list.resize(n);
        }
        void addEdge(int a,int b){
            list[a].push_back(b);
            list[b].push_back(a);
        }
        void printGraph(){
            std::vector< std::vector<int> >::const_iterator vertex;
            std::vector<int>::const_iterator adjacent;
            int i=0;
            for(vertex=list.begin();vertex != list.end() ; ++vertex )
            {
                std::cout<<"Adjacent of "<<i<" is : ";
            for(adjacent = vertex->begin();adjacent != vertex->end();++adjacent){
                std::cout<<*adjacent<<" ";
            }  
            i+=1;      
            std::cout<<"\n";
            }
                }
   };

main(){
    graph gh(5);
    gh.addEdge(1,2);
    gh.addEdge(1,3);
    gh.addEdge(2,4);
    gh.addEdge(2,5);
    gh.addEdge(3,5);
    gh.addEdge(4,5);
    gh.addEdge(4,6);
    gh.addEdge(5,6);
    gh.printGraph();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

在您的主要内容中,定义gh(5)分配大小为5的向量,然后使用参数addEdge的{​​{1}}方法尝试访问(5,6),但列表为5条目为list[5]list[0],list[1],list[2],list[3],。所以我猜list[4]给出了分段错误,因为它超出了向量的范围。