std :: set迭代器自动const [英] std::set iterator automatically const

查看:98
本文介绍了std :: set迭代器自动const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为简单起见,我已经提取了问题并更改了名称,等等。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆