【问题标题】:C++ code, Read-only variable is not assignableC++ 代码,只读变量不可赋值
【发布时间】:2014-02-09 22:51:22
【问题描述】:

这是 C++ 代码。我很困惑为什么取消引用迭代器告诉我变量是只读的?它是 Node 类的公共成员。我的错误是什么?

adjTable 是一组 Node 元素 - 请参阅下面的声明。

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();
};

【问题讨论】:

标签: c++


【解决方案1】:

std::set 的元素是不可变的。所以你不能修改它们。如果您希望能够修改它们,则需要不同的数据结构。

【讨论】:

    【解决方案2】:

    更改映射或集合的键可能会导致未定义的行为,因为您的映射/集合依赖于键值来维持顺序。如果您的 SortNodeSet 函数/函子不使用 colour 字段,这很可能是图形算法中的逻辑选择,您可以将此字段定义为 mutable 字段,即

    mutable short colour;
    

    这告诉编译器,如果您更改 colour 字段,则不会认为节点已更改。

    【讨论】:

      【解决方案3】:

      由于您的比较仅基于 ID,您可能希望使用 std::map&lt;short, Node&gt; 来启用基于 ID 的查找。

      然后,将nodeID 成员变量设为const,因为更改 ID 会中断查找。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多