kekyc
kekyc

Reputation: 327

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

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’ 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

Upvotes: 1

Views: 1848

Answers (1)

Brian Bi
Brian Bi

Reputation: 119239

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.

Upvotes: 8

Related Questions