Tyhja
Tyhja

Reputation: 135

Map in Map Map.Clear() error

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;

I only chanced across mutable as an option in a similar but not the same question. My question is am I doing the right thing, or if there are any pitfalls in doing so? Thank you for your help in advance.

//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

Upvotes: 1

Views: 963

Answers (3)

Ajay
Ajay

Reputation: 18431

The code given by you is not correct. destroy should have been a const-member of class, but you have shown it as global function. Since/If destroy is const method, clear wouldn't work on it.

Upvotes: 0

iammilind
iammilind

Reputation: 69998

Have you tried, putting simple iterator ?

AList::iterator a;

const_iterator doesn't allow the members to be modifiable (some what like const in normal context).

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223083

You should use iterator instead of const_iterator, if your intent is to call clear. const_iterator is for cases where you are calling only const member functions.

Using mutable is not appropriate for this situation. Only mark member variables mutable if they are not part of the object's visible state, e.g., cached data.

Upvotes: 1

Related Questions