1

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.

5
  • 3
    You marked the member function const, but then you try to modify the object. Commented Aug 10, 2021 at 8:30
  • You can make word_count mutable, but that defeats the purpose Commented Aug 10, 2021 at 8:32
  • @molbdnilo Thanks, i'm so stupid, you are right. Commented Aug 10, 2021 at 8:35
  • 1
    You're not stupid, it's a vague and misleading error message. (It looks like an IntelliSense message, and those are often not very good. You might get a better message if you compile the code.) Commented Aug 10, 2021 at 8:37
  • @molbdnilo yeah, i will, thanks again. Commented Aug 10, 2021 at 8:53

1 Answer 1

3

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)); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.