Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function pointers for std::unordered_map

Tags:

c++

std

c++11

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;
like image 972
user1095108 Avatar asked Mar 11 '13 08:03

user1095108


1 Answers

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.

like image 154
sellibitze Avatar answered Nov 03 '22 16:11

sellibitze