Home > Software engineering >  How can I return unordered_map with a hash function to something expecting just `unordered_map<st
How can I return unordered_map with a hash function to something expecting just `unordered_map<st

Time:11-05

I want to implement an unordered_map<string, string> that ignores case in the keys. My code looks like:

    std::unordered_map<std::string, std::string> noCaseMap()
    {
        struct hasher {
            std::size_t operator()(const std::string& key) const {
                return std::hash<std::string>{}(toLower(key));
            }
        };
        std::unordered_map<std::string, std::string, hasher> ret;
        return ret;
    }

but XCode flags the return statement with this error:

foo.cpp:181:20 No viable conversion from returned value of type 'unordered_map<[2 * ...], hasher>' to function return type 'unordered_map<[2 * ...], (default) std::hash<std::string>>'

I tried casting ret to <std::unordered_map<std::string, std::string>>, but XCode wasn't having it.

I tried making my hasher a subclass of std::hash<std::string> but that made no difference.


Edit: this is a slight oversimplification of the problem; I know I also have to implement a case-insensitive equal_to() functor as well.

CodePudding user response:

You can't. There's a reason it's part of the type: efficiency. What you can do is e.g. store everything lowercase. If you need both lowercase and case-preserving, you might need two maps; but, at this point, I'd consider requesting an interface change.

  • Related