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

kek*_*kyc 1 c++ compiler-errors stdmap c++11

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

std::map<int,int> pol;
Run Code Online (Sandbox Code Playgroud)

地图填充了数据,然后我开始处理它.

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;
              }
}
Run Code Online (Sandbox Code Playgroud)

开始 - >第一次 - 进一步我得到了非常大的输出,有错误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
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 7

它是只读的,因为如果允许您自由修改地图中的键,则会违反地图使用的数据结构的不变量(通常是红黑树).

您需要删除元素并使用递减的值将其重新添加.这可确保节点位于树中的正确位置.

  • @synchronizer没有没有; 如果你需要这样做,这意味着`map`不是你的应用程序的正确数据结构 (3认同)