2014-02-09 34 views
1

這裏是C++代碼。我很困惑,爲什麼解引用迭代器告訴我變量是隻讀的?它是Node類的公共成員。我的錯誤是什麼?C++代碼,只讀變量不可賦值

adjTable是一組節點的元素 - 見以下聲明的。

Cells::iterator pos = adjTable.find(*thisNode); 
if (pos == adjTable.end()) { // Did we find it? 
    NSLog(@"Not found"); 
// What to do here if node not found 
} 
// We found the node - mark it as grey in the table 
(*pos).colour = grey; // <<<<<<<< this is the line with the issue 

這裏是聲明等。(它似乎沒有以正確格式)

class Node { // Define a single node a.k.a. matrix cell 
public: 
    short nodeID;   // the tag from the cell 
    short colour;   // for tri-colour used in traversing 
    std::vector<short>adjs; // nodeIDs of adjacent nodes 

    // Ctors 
    Node(){}; 
    Node(short ID, short col, std::vector<short>adjs) 
     : nodeID(ID), colour(col), adjs(adjs){} 
    // Dtors 
    ~Node(){}; 
    // operators 
    bool operator<(const Node& rhs) const{ 
     return nodeID < rhs.nodeID; 
    } 
    bool operator==(const Node& rhs) const{ 
     return nodeID == rhs.nodeID; 
    } 
}; 

typedef std::set<Node,SortNodeSet> Cells; 
class MakeTable { 
public: 
    MakeTable(){}; 
    ~MakeTable(){}; 
    Cells makeTable(); 
}; 
+0

有關'std :: set'修改的其他SO信息http://stackoverflow.com/questions/908949/what-happens-when-you-modify-an-element-of-an-stdset – txtechhelp

+0

此鏈接幫助我。我選擇使用const_cast ((* pos).colour)= gray; – pteeson

回答

1

一個std::set的元素是不可變的。所以你不能修改它們。如果你想修改它們,你需要一個不同的數據結構。

0

因爲你的比較僅基於ID,您可能需要使用一個std::map<short, Node>,使基於ID的查找。

然後,使nodeID成員變量const,因爲更改ID將打破查找。

1

爲您的地圖/套取決於密鑰值維持秩序不斷變化的地圖或設置鍵可能會導致不確定的行爲。如果您SortNodeSet函數/仿函數不使用colour場,這很可能和圖形algroithms一個合乎邏輯的選擇,你可以定義這個字段作爲mutable領域,即。

mutable short colour; 

這告訴節點不被認爲是編譯器改變如果你改變了colour領域。