这可能很简单,但我似乎无法解决。在我的内部Vertex
,我有一个std::list<Edge>
但是当我尝试调用它的方法时,push_front
我得到一个错误,说list
是const
并且我无法推动它。我认为出于某种原因,编译器正在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]