使用 std::map 时只读成员的错误递减
Error decrement of read-only member when using std::map
我使用多义词并将它们作为度数和系数保存在 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;
}
}
从它开始 - >首先 - 进一步,我得到了大量的输出,错误如下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
它是只读的,因为如果您被允许自由修改映射中的键,您将违反映射使用的数据结构的不变性(通常是红黑树(。
您需要删除该元素,然后使用递减的值重新添加它。这可确保节点位于树中的正确位置。
相关文章:
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++错误消息*成员参考.**初学者*
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 在运算符重载定义中使用成员函数(const错误)
- 错误:请求非类类型为"MULTIMEDIA_FILME [500]"的成员|
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 静态成员函数使用相同的名称时出现模板类型名称错误
- 为什么即使我声明了朋友类,我也会收到错误"无法访问类中声明的私人成员"
- 为什么我在空指针错误(链表)中获取成员访问权限
- WinLamb 错误:成员初始化非法
- 类成员值的合法或错误成员用法
- for 循环说 - 错误 成员引用基类型"int [13]"不是结构或联合
- C++错误:成员声明末尾的预期“;”
- C++:错误:成员访问不完整的类型,未使用的参数[-Werror,-Wunused-parameter]
- 错误:成员函数不能在其类之外声明
- 初始化 cpp 文件中的私有静态成员变量.错误:成员是私有的
- 错误:成员访问不完整类型:前向声明
- 错误:成员不可访问
- 指向基类错误成员函数的指针