使用STD :: MAP的错误减少读取成员
我使用 polinom 并将它们作为度数和系数保存在 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
或 错误:分配只读成员 'std::pair
为什么它是只读的?我该如何修复它?
$ g++ --version
g++ (Debian 6.3.0-5) 6.3.0 20170124
I work with polinoms and keep them in std::map as degrees and coefficients. Here's the code pieces:
std::map<int,int> pol;
Map is filled with data and then I begin to process it.
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;
}
}
And beginning from it->first-- and further I'm getting very big amount of output with errors like error: decrement of read-only member ‘std::pair<const int, int>::first’
it->first--;
^~
or error: assignment of read-only member ‘std::pair<const int, int>::first’
Why is it readonly? How can I fix it?
it->first = it->first - 1;
$ g++ --version
g++ (Debian 6.3.0-5) 6.3.0 20170124
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它是只读的,因为如果允许您自由修改映射中的键,则会违反映射使用的数据结构(通常是红黑树)的不变量。
您需要删除该元素并将其添加回减少的值。这确保了节点将位于树中的正确位置。
It's read-only because if you were allowed to freely modify the key in the map, you would violate the invariant of the data structure the map uses (typically a red-black tree).
You need to remove the element and add it back in with the decremented value. This ensures that the node will be in the correct place in the tree.