1

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?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

1 Answers1

5

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);
spencercw
  • 3,320
  • 15
  • 20
  • looks like a bug in the design of stl::set implementation...I can change by iterator stl::vector,for example.The role of iterator is to get actual object of container. – YAKOVM Feb 26 '12 at 10:52
  • 2
    Right, but it doesn't matter if you change the value of something in a `vector`. A `set` needs to know exactly what is in it in order to work properly. – spencercw Feb 26 '12 at 10:53