使用std::map时只读成员的错误减量
Error decrement of read-only member when using std::map
我使用多项式并将它们作为度数和系数保存在 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;
}
}
从 it->first-- 开始,我得到了非常大量的输出,其中包含诸如 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
它是 read-only 因为如果允许您自由修改映射中的键,您将违反映射使用的数据结构(通常是 red-black 树)的不变性。
您需要删除该元素,然后将其添加回已减少的值。这确保节点将位于树中的正确位置。
我使用多项式并将它们作为度数和系数保存在 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;
}
}
从 it->first-- 开始,我得到了非常大量的输出,其中包含诸如 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
它是 read-only 因为如果允许您自由修改映射中的键,您将违反映射使用的数据结构(通常是 red-black 树)的不变性。
您需要删除该元素,然后将其添加回已减少的值。这确保节点将位于树中的正确位置。