我有一个包含 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;}
//.....
}
每个 Cell
都有 m_x
和 m_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;
}
};
我运行以下命令以找到“实际单元格”:
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);
itCell->setColor(GRAY) 出现编译错误; itCell->setParentId(cIdFrom);
:
cannot convert 'this' pointer from 'const Cell' to 'Cell &'
如何解决?
最佳答案
通过迭代器更改 set
的元素的值是不合法的,因为 set
无法知道您更改了什么并且会使它无效.如果您想像这样更改它,则必须将其删除并重新插入您所做的更改。
Cell newCell(*itCell);
newCell.setColor(GRAY);
m_cells.erase(itCell);
m_cells.insert(newCell);
关于c++ - STL 集合迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9452321/