Map in Map Map.Clear() error

Map in Map Map.Clear() error

本文关键字:Map error Clear in      更新时间:2023-10-16
void destroy()
{
    AList::const_iterator a;
    for(a = AList.begin(); a != AList.end();)
    {
        if(!a->second.BList.empty())
            a->second.BList.clear();//will give error if not mutable
    }
}
typedef std::map<unsigned int,int> bmap;
typedef std::map<unsigned int,someStruct> Alist;
typedef struct someStruct
{
    float x,y,z;
    bmap BList; //needs to be mutable for Blist.clear() above.
    //mutable bmap BList; //<---like this
} someStruct;

我只是在一个类似但不相同的问题中改变了可变选项。我的问题是,我做的是对的吗,或者这样做是否有陷阱?提前感谢您的帮助。

//error given: (if otherwise not mutable)
// error: passing 'const AList' as 'this' argument of 'void std::map<_Key, _Tp, _Compare, _Alloc>::clear() [with _Key = unsigned int, _Tp = int, _Compare = std::less<unsigned int>, _Alloc = std::allocator<std::pair<const unsigned int, int> >]' discards qualifiers

您应该使用iterator而不是const_iterator,如果您的意图是调用clearconst_iterator用于只调用const成员函数的情况。

使用mutable不适合这种情况。如果成员变量不是对象可见状态的一部分,例如缓存的数据,则只标记mutable

你试过放简单的iterator吗?

AList::iterator a;

const_iterator不允许修改成员(有点像正常上下文中的const)。

您给出的代码不正确。destroy应该是类的const成员,但您将其显示为全局函数。因为/If destroy是const方法,clear不能在它上面工作