stl set iterator

2019-06-04 07:24发布

I have an stl set with objects of Cell class

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;}
         //.....
}

Each Cell has m_x and m_y (member) coordinates + additional data members(m_t,m_color,m_pCellId,m_regNum)

comapareCells class is used to find the cell only based on its actual m_x and m_y coordinates:

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

};

I run the following in order to find "actual cell": c is a cell which has only needed cell coordinates. It is used to find the actual cell, contained in the cet, having given coordinates and try to make some operations on the actual cell:

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

I get compilation error/s foritCell->setColor(GRAY); itCell->setParentId(cIdFrom);:

cannot convert 'this' pointer from 'const Cell' to 'Cell &'

How can it be solved?

1条回答
我只想做你的唯一
2楼-- · 2019-06-04 08:10

It is not legal to change the value of a set's elements through an iterator because the set has no way of knowing what you have changed and would invalidate it. If you want to change it like that you would have to remove it and reinsert it with your changes.

Cell newCell(*itCell);
newCell.setColor(GRAY);
m_cells.erase(itCell);
m_cells.insert(newCell);
查看更多
登录 后发表回答