0

这可能很简单,但我似乎无法解决。在我的内部Vertex,我有一个std::list<Edge>但是当我尝试调用它的方法时,push_front我得到一个错误,说listconst并且我无法推动它。我认为出于某种原因,编译器正在std::list<Edge>const std::list<Edge>. 我知道我的代码设置得不是很好,但这只是家庭作业,所以我采取了一些捷径。

头文件:

#ifndef GRAPH_H
#define GRAPH_H

#include <set>
#include <list>

class Edge{
public:
    unsigned int to;
    unsigned int weight;
};

class Vertex{
public:
    unsigned int id;
    std::list<Edge> edges;

    bool operator<(const Vertex& other) const{
        return id < other.id;
    }
};

class Graph{

public:
    void add_vertex(unsigned int id);
    void add_edge(unsigned int from, unsigned int to, unsigned int weight);
    std::set<Vertex> get_vertices();
    std::list<Edge> get_edges(unsigned int id);

private: 
    std::set<Vertex> _vertices;
    unsigned int size = 0;


};

导致错误的行:

void Graph::add_edge(unsigned int from, unsigned int to, unsigned int weight) 
{
Vertex find_vert;
find_vert.id = from;
set<Vertex>::iterator from_v = _vertices.find(find_vert);
Edge new_edge;
new_edge.to = to;
new_edge.weight = weight;

from_v->edges.push_front(new_edge); // ERROR HERE
}

运行中的编译器错误消息g++ -c Graph.cpp

Graph.cpp:23:38: error: passing ‘const std::list<Edge>’ as ‘this’ argument of ‘void std::list<_Tp,
_Alloc>::push_front(const value_type&) [with _Tp = Edge; _Alloc = std::allocator<Edge>; std::list<_Tp,
_Alloc>::value_type = Edge]’ discards qualifiers [-fpermissive]
4

1 回答 1

4

a 的内容std::set是隐式const的,因为更改内容可能会使它们的排序顺序无效。

这使得这里from_v隐含const

set<Vertex>::iterator from_v = _vertices.find(find_vert);

你的错误是告诉你你正在尝试修改一个const对象。

   from_v->edges.push_front(new_edge);
// ^^^^^^ const  ^^^^^^^^^^ non-const behavior
于 2013-03-31T22:58:22.143 回答