【问题标题】:no instance of overloaded function std::unordermap.insert没有重载函数 std::unordered_map.insert 的实例
【发布时间】:2021-10-13 19:30:32
【问题描述】:

我声明了一个流类,但是在定义它的成员函数时,我想往私有成员unordered_map中插入东西时总是报错,请问如何解决? 流.h

#include <unordered_map>

class stream
{
private:
    std::unordered_map<size_t, std::string> word_count;
public:
    void reassemblestream() const;
};

流.cpp

#include"stream.h"
using namespace std;
void stream::reassemblestream() const
{
    static  size_t a = 1;
    string fe = "dfi";
    word_count.insert({ 1,"dfs" });
    word_count.insert(make_pair(a, fe));
}

word_count.insert 函数的 stream.cpp 中发生错误。 这是错误信息:

E1087 没有重载函数“std::unordered_map<_kty _ty _hasher _keyeq _alloc>::insert [其中 _Kty=size_t, _Ty=std::string, _Hasher=std:: hash, _Keyeq=std::equal_to, _Alloc=std::allocator>]" 实例(对象包含阻止匹配的类型限定符)

我使用 Visual Studio 2019。

【问题讨论】:

  • 您标记了成员函数const,但随后您尝试修改该对象。
  • 你可以制作word_count mutable,但这违背了目的
  • @molbdnilo 谢谢,我太傻了,你是对的。
  • 你不傻,这是一个模糊和误导性的错误信息。 (它看起来像一个 IntelliSense 消息,这些消息通常不是很好。如果你编译代码,你可能会得到更好的消息。)
  • @molbdnilo 是的,我会的,再次感谢。

标签: c++ c++11 stl


【解决方案1】:

如果使用clang++ 构建程序,我们会得到更清晰的错误消息:

source>:17:16: error: no matching member function for call to 'insert'
    word_count.insert({ 1,"dfs" });
    ~~~~~~~~~~~^~~~~~
/opt/compiler-explorer/gcc-11.1.0/lib/gcc/x86_64-linux-gnu/11.1.0/../../../../include/c++/11.1.0/bits/unordered_map.h:557:7: note: candidate function not viable: 'this' argument has type 'const std::unordered_map<size_t, std::string>' (aka 'const unordered_map<unsigned long, basic_string<char>>'), but method is not marked const
      insert(value_type&& __x)

只要去掉const限定符,因为你是通过调用insert函数修改数据成员,函数reassemblestream不能标记为const(相关question为const成员函数):

#include <unordered_map>
#include <string>

class stream
{
private:
    std::unordered_map<size_t, std::string> word_count;
public:
    void reassemblestream();
};


void stream::reassemblestream() 
{
    static  size_t a = 1;
    std::string fe = "dfi";
    word_count.insert({ 1,"dfs" });
    word_count.insert(make_pair(a, fe));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-11
    • 2016-03-16
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 1970-01-01
    相关资源
    最近更新 更多