I'm implementing the following method to delete an element from an associative table (map
) with map::erase()
:
//Method in gestion.cpp
void Gestion::EliminateObject(string nomobjetg) const{
auto it = objectname.find(nameobjectg);
if (it == objectname.end())
cout << "Object not found!" << endl;
else
objectname.erase(it); //The error is reported in this line
}
In the header I have defined the following:
//gestion.h
#include "objects.h"
#include <list>
#include <iostream>
#include <string>
#include <memory>
#include <map>
using namespace std;
typedef std::shared_ptr<Objects> ObjPtr;
typedef map<string, ObjPtr> Objectmap;
class Gestion
{
private:
Objectmap objectname;
public:
Gestion(Objectmap objectname, Groupmap groupname);
virtual ~Gestion() {}
virtual void EliminateObject(string nameobjectg) const;
};
Where ObjPtr
is a virtual pointer of objects of type Objects
.
When I compile I get this error:
error: passing ‘const Objectmap {aka const std::map<std::basic_string<char>, std::shared_ptr<Objects> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp, _Compare, _Alloc>::iterator std::map<_Key, _Tp, _Compare, _Alloc>::erase(std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator) [with _Key = std::basic_string<char>; _Tp = std::shared_ptr<Objects>; _Compare = std::less<std::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >; std::map<_Key, _Tp, _Compare, _Alloc>::iterator = std::_Rb_tree_iterator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >; std::map<_Key, _Tp, _Compare, _Alloc>::const_iterator = std::_Rb_tree_const_iterator<std::pair<const std::basic_string<char>, std::shared_ptr<Objects> > >]’ discards qualifiers [-fpermissive]
objectname.erase(it);
Why is this line reporting this error? I've seen some other posts with this type of error but in those cases the root cause of the problem is related to how the method is declared (const
). In this case the method involved in the problem is erase
and I cannot modify it.
void Gestion::EliminateObject(string nomobjetg) const
You are trying to modify objectname
with your call to objectname.erase(it)
, and a const
function will not let you do that, unless objectname
is mutable.
Remove const:
void Gestion::EliminateObject(string nomobjetg)
or
Make objectname
mutable
mutable Objectmap objectname;