c++ - 当使用 map::erase() "error: passing ' const ** *' as ' '***' 的这个参数丢弃限定符 [-fpermissive]”报告

标签 c++ iterator erase qualifiers

我正在实现以下方法,使用 map::erase() 从关联表 (map) 中删除一个元素:

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

在 header 中我定义了以下内容:

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

其中 ObjPtrObjects 类型对象的虚拟指针。

当我编译时出现这个错误:

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);

为什么这一行会报这个错?我已经看到其他一些帖子出现此类错误,但在那些情况下,问题的根本原因与方法的声明方式 (const) 有关。在这种情况下,问题涉及的方法是erase,我无法修改它。

最佳答案

void Gestion::EliminateObject(string nomobjetg) const

您正在尝试通过调用 objectname.erase(it) 来修改 objectname,而 const 函数不允许您这样做除非 objectname可变的

删除常量:

void Gestion::EliminateObject(string nomobjetg)

使objectname可变

mutable Objectmap objectname;

关于c++ - 当使用 map::erase() "error: passing ' const ** *' as ' '***' 的这个参数丢弃限定符 [-fpermissive]”报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35676311/

相关文章:

HTML5 Canvas 橡皮擦工具 不透白 白色

c# - 这可能吗?在 C# 中调用托管 C++ 结构构造函数

c++ - ofstream.put();不写整数?

python - 遍历列表并在 Python 中漂亮地处理 StopIteration

c++ - 如何保存 min_element 结果的位置?

c++ - 使用模板实现 const 范围

c++ - 在 C++ 中从 3D vector 中删除元素

linux -/dev/zero还是安全删除?

c++ - 如何使用带有除空格以外的其他分隔符的 istringstream 拆分字符串?

c++ - 在 cmake 中启用 gpu 时为 tensorflow 编译静态库 c++ 时出错