2013-03-31 41 views
0

這可能是一件很簡單的事情,但我似乎無法解決這個問題。在我的Vertex中,我有一個std::list<Edge>,但是當我嘗試調用其上的方法時,如push_front,我收到一個錯誤消息,說listconst,我無法進入它。我認爲出於某種原因編譯器正在將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] 
+3

你可能正在用'const'限定符在函數中執行該行 – James

+0

什麼是'from_v'定義爲? – 0x499602D2

+0

'from_v'是'set :: iterator from_v = _vertices.find(find_vert);' – seanwatson

回答

4

一個std::set的內容是隱含const,因爲改變內容庫爾d使其排序順序無效。

這使得from_v暗示const在這裏。

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

而你的錯誤是告訴你,你要修改const對象。

​​
+0

ahhh更合理。謝謝! – seanwatson