std::set 迭代器自动 const

std::set iterator automatically const(std::set 迭代器自动 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

基础教程推荐