stl设置迭代器

Yak*_*kov 1 c++ iterator stl set

我有一个带有Cell类对象的stl集

class Cell
{
public:
    //Ctor/Dtor
    Cell(size_t cellId=0,int x =0,int y = 0,size_t t = 0):m_cellId(cellId),m_x(x),m_y(y),m_t(t),m_color(WHITE),m_pCellId(0),m_regNum(0){}
    ////////////////////
    //    Mutators    //
    ////////////////////
    void schedNode(size_t t,int nodeId){m_sched[t] = nodeId;}
    void setColor(color c){m_color = c;}
    void setParentId(size_t pId){m_pCellId = pId;}
         //.....
}
Run Code Online (Sandbox Code Playgroud)

每个Cell都有m_xm_y(成员)坐标+其他数据成员(m_t,m_color,m_pCellId,m_regNum)

comapareCells类仅用于根据实际的m_x和m_y坐标查找单元格:

class comapareCells
{
public:
    bool operator()(const Cell& lCell,const Cell& rCell)
    {
        if(lCell.getX() < rCell.getX())
            return true;
        else if(lCell.getX() == rCell.getX())
            return (lCell.getY() < rCell.getY());
        else
            return false;
    }

};
Run Code Online (Sandbox Code Playgroud)

我运行以下命令以找到"实际单元格": c是一个只需要单元格坐标的单元格.它用于查找包含在cet中的实际单元格,它给出了坐标并尝试对实际单元格进行一些操作:

set<Cell,comapareCells>::iterator itCell;
    if((itCell = m_cells.find(c)) == m_cells.end())
        return;
    if(itCell->getColor() != WHITE)
        return;
    itCell->setColor(GRAY);
    itCell->setParentId(cIdFrom);
Run Code Online (Sandbox Code Playgroud)

我得到编译错误itCell->setColor(GRAY); itCell->setParentId(cIdFrom);:

无法将'this'指针从'const Cell'转换为'Cell&'

怎么解决?

spe*_*rcw 5

set通过迭代器更改元素的值是不合法的,因为set无法知道您已更改的内容并使其无效.如果您想要更改它,则必须将其删除并重新插入更改.

Cell newCell(*itCell);
newCell.setColor(GRAY);
m_cells.erase(itCell);
m_cells.insert(newCell);
Run Code Online (Sandbox Code Playgroud)

  • 是的,但如果你改变'vector`中的某些东西的价值并不重要.`set`需要准确知道其中的内容才能正常工作. (2认同)