我使用多义词并将它们作为度数和系数保存在 std::map 中。以下是代码片段:
std::map<int,int> pol;
地图充满了数据,然后我开始处理它。
for(std::map<int,int>::iterator it = pol.begin(); it != pol.end(); it++) {
if( it->first != 0 ) {
it->second *= it->first;
it->first--;
}
else {
it->first = 0;
it->second = 0;
}
}
从它开始 - >首先 - 进一步,我得到了大量的输出,错误如下error: decrement of read-only member ‘std::pair<const int, int>::first’
it->first--;
^~
或error: assignment of read-only member ‘std::pair<const int, int>::first’
it->first = it->first - 1;
为什么它是只读的?我该如何解决它?
$ g++ --version
g++ (Debian 6.3.0-5) 6.3.0 20170124
它是只读的,因为如果您被允许自由修改映射中的键,您将违反映射使用的数据结构的不变性(通常是红黑树(。
您需要删除该元素,然后使用递减的值重新添加它。这可确保节点位于树中的正确位置。