std::set iterator automatically const(std::set 迭代器自动 const)
问题描述
可能重复:
C++ STL 集更新很繁琐: 我不能原地改变元素
为了简单起见,我已经提取了问题并更改了名称.
I have extracted the problem and changed names and so for simplicities sake.
基本上我实例化一个类并将其存储在 std::set 中,稍后我想引用该类,以便我可以检查它的值并修改它们...
Basically I instantiate a class and I stock it in a std::set, later on I'd like to have a reference to the class so that I can check its values and modify them...
简化代码:
MyClass tmpClass;
std::set<MyClass > setMyClass;
setMyClass.insert(tmpClass);
std::set<MyClass >::iterator iter;
iter=setMyClass.begin();
MyClass &tmpClass2=*iter;
和错误:
error C2440: 'initializing' : cannot convert from 'const MyClass' to 'MyClass &'
(我也删除了部分错误消息MVB::Run::"以清除它.)
(I removed parts of the error message, "MVB::Run::" to clear it up too.)
如果我在最后一行代码中添加一个前面的const",那么一切正常,但我无法更改值...
if I add a preceding 'const' to the last line of code then everything works well but then I can't change the value...
这是正常行为吗?比如说,我必须删除数据、更改值并重新放回去?
Is this normal behaviour and I have to, say, remove the data, change values and put it back again?
我感觉这与集合的排序有关,但我不会触及用于排序的变量.
I have the feeling that this has something to do with the sorting of the set but I won't touch the variables that are used for the sorting.
推荐答案
我确定你 不会触及用于排序的变量
,你可以通过使用const_cast 像这样:
I you are certain you won't touch the variables that are used for the sorting
the you could work around this by using a const_cast like this:
MyClass tmpClass;
std::set<MyClass > setMyClass;
setMyClass.insert(tmpClass);
std::set<MyClass >::iterator iter;
iter=setMyClass.begin();
const MyClass &tmpClass2=*iter;
MyClass &tmpClass3 = const_cast<MyClass&>(tmpClass2);
或者,您可以将要更改的类的成员声明为可变的.
Alternatively, you could declare the members of the class that you intend to change as mutable.
这篇关于std::set 迭代器自动 const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::set 迭代器自动 const


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01