这可能是一件很简单的事情,但我似乎无法解决这个问题。在我的Vertex
中,我有一个std::list<Edge>
,但是当我尝试调用其上的方法时,如push_front
,我收到一个错误消息,说list
是const
,我无法进入它。我认为出于某种原因编译器正在将std::list<Edge>
转换为const std::list<Edge>
。我知道我的代码设置得不是很好,但它只是作业,所以我正在采取一些快捷方式。C++编译器将列表转换为常量列表
头文件:
#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]
你可能正在用'const'限定符在函数中执行该行 – James
什么是'from_v'定义为? – 0x499602D2
'from_v'是'set :: iterator from_v = _vertices.find(find_vert);' –
seanwatson