1

The following code example will not compile, however it can be made to compile by removing the const specifier before std::string as the unordered map key.

#include <unordered_map>
#include <utility>
#include <string>
#include <iostream>

int main()
{

    int myint = 5;
    std::unordered_map<const std::string, int*> map;
    map.insert({"string", &myint});
    std::cout << *map.at("string") << std::endl;

    return 0;
}

Why does this code not compile when const std::string is used as a key, when std::string works?

9
  • @NO_NAME wrong duplicate Commented May 29, 2018 at 21:15
  • What's the point of this? The key in the map is a copy of the original string. Commented May 29, 2018 at 21:16
  • @Barmar To be explicit? Commented May 29, 2018 at 21:17
  • I would like to know why map and unordered_map differ in this regard. It's a shame the duplicate doesn't seem to address this question. Commented May 29, 2018 at 21:18
  • 1
    @NO_NAME because it doesn't answer the question asked: WHY does it not compile Commented May 29, 2018 at 21:21

1 Answer 1

4

std::unordered_map uses std::hash by default for the hash function. It uses the type of the key for the template type of std::hash. <string> specializes std::hash for std::string but since the key type is const std::string, there is no matching specialization and compilation fails.


Really though, using std::unordered_map<std::string, int*> will do exactly what you need. The key in all associative containers is const already for you so there is no reason to mark in const in the template parameters.

Sign up to request clarification or add additional context in comments.

9 Comments

Is this a "bug"?
@user3728501 in where?
@user3728501 It's not a code bug. You might call it a language bug (the standard should say there needs to be a const version) but since keys in associative containers are made const it's not really needed. std::unordered_map<std::string, int*> will do the exact same thing and actually compile.
@SergeyA Why would every developer in the world who wished to put the const specifier there also implement their own hash function?
Every developer in the world could think about 'why' they want to do it, and find out there is no good reason for it?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.