gpt4 book ai didi

c++ - 使用 std::map 时只读成员的错误递减

转载 作者:太空宇宙 更新时间:2023-11-03 10:40:00 25 4
gpt4 key购买 nike

我使用多项式并将它们作为度数和系数保存在 std::map 中。这是代码片段:

std::map<int,int> pol;

map 充满了数据,然后我开始处理它。

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

最佳答案

它是只读的,因为如果允许您自由修改映射中的键,您将违反射(reflect)射使用的数据结构(通常是红黑树)的不变性。

您需要删除该元素,然后将其添加回具有递减值的元素。这可确保节点位于树中的正确位置。

关于c++ - 使用 std::map 时只读成员的错误递减,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42149614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com