简体   繁体   中英

function pointers for std::unordered_map

There are sites like this one:

http://www.cplusplus.com/reference/unordered_map/unordered_map/

That say, one can provide a function pointer, instead of a class, for the Hash and Pred argument of the std::unordered_map class template. However, there are no examples, and I haven't managed to get this feature to work, if it is possible at all. Nonworking example:

bool unordered_eq(const char* const s1, const char* const s2)
{
  return !std::strcmp(s1, s2);
}

std::size_t unordered_hash(char const* s)
{
  return std::hash<std::string>()(s);
}

std::unordered_map<char const*, std::string,
  unordered_hash, unordered_eq> hashmap;

That say, one can provide a function pointer, instead of a class

No, that's a misunderstanding. You can provide a function pointer instead of a function object to the constructor . The template parameter is still a type - in this case the type of a function pointer. So, you have to write

typedef unordered_map<
            char const*, string,
            size_t(*)(char const*), // type for hashing
            bool(*)(char const*, char const*) // type for equality
        > yourmaptype;

yourmaptype hm (
        4, // minimum number of buckets
        &unordered_hash, // function address for hashing
        &unordered_eq, // function address for equality
    );

Your standard library defines a default value for the first parameter but this default value is not standardized. It seems there is no way of keeping your vendor-specific default value for n and at the same time set the functors' values. My use of 4 is rather arbitrary here.

You should consider the use of default-constructible function objects instead. Not only this will allow you to get away without specifying the minimim bucket size, it also will be potentially faster since functors are much easier to inline for the compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM