简体   繁体   English

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

[英]Error decrement of read-only member when using std::map

I work with polinoms and keep them in std::map as degrees and coefficients. 我使用polinoms,并将它们作为度数和系数保存在std :: map中。 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--; ^~ 开始- >首先 -进一步,我得到了大量的输出,并出现诸如error: decrement of read-only member 'std::pair<const int, int>::first' it->first--; ^~ 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' it->first = it->first - 1; 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; Why is it readonly? 为什么它是只读的? How can I fix it? 我该如何解决?

$ g++ --version
g++ (Debian 6.3.0-5) 6.3.0 20170124

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. 这样可以确保该节点将在树中的正确位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM