c++templates

if value of a hash map is also a hash container, e.g., unordered_map<int, unordered_set<...>>, how to specify customized hash & equal for the value?


Say now I have hash and equal functions ready for an unordered_set

auto equalFunc = [](...){...};
auto hashFunc  = [](...){...};

If the unordered_set is used solely, I know I can do the following to specify my DIY hash and equal:

std::unordered_set<std::pair<int,int>, decltype( hashFunc ), decltype( equalFunc )> mySet( 0, hashFunc, equalFunc );

However, now suppose the unordered_set is to be used as value of std::unordered_map, how can I specify the hash and equal?

std::unordered_map<int, std::unordered_set<std::pair<int,int>, decltype( hashFunc ), decltype( equalFunc )>> myMap( ...how? );

Solution

  • You need to do the std::unordered_set construction, with the functions, when you insert an element into the map:

    myMap[some_key] = std::unordered_set<std::pair<int,int>, decltype( hashFunc ), decltype( equalFunc )>( 0, hashFunc, equalFunc );
    

    It would of course be simpler if you used an alias for the type:

    using mySetType = std::unordered_set<std::pair<int,int>, decltype( hashFunc ), decltype( equalFunc )>;
    
    // ...
    
    myMap[some_key] = mySetType( 0, hashFunc, equalFunc );