jam buck
jam buck

Reputation: 33

no instance of overloaded function std::unordermap.insert

I declared a stream class, but when defining its member function, it always reports an error when I want to insert something into the private member unordered_map, I want to ask How to solve this? stream.h

#include <unordered_map>

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

stream.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));
}

error happen in stream.cpp of word_count.insert funcion. This is the error information:

E1087 There is no overloaded function "std::unordered_map<_Kty, _Ty, _Hasher, _Keyeq, _Alloc>::insert [where _Kty=size_t, _Ty=std::string, _Hasher=std:: hash<size_t>, _Keyeq=std::equal_to<size_t>, _Alloc=std::allocator<std::pair<const size_t, std::string>>]" instance (object contains type qualifiers that prevent matching)

I use visual studio 2019.

Upvotes: 1

Views: 861

Answers (1)

prehistoricpenguin
prehistoricpenguin

Reputation: 6326

If build the program with clang++, we get more clear error messages:

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)

Just remove the const qualifiers, since you are modifying the data member by calling the insert function, the function reassemblestream can't be marked as const(related question for const member function):

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

Upvotes: 3

Related Questions