C++ Logo

std-discussion

Advanced search

Re: Trying to solve how to do a std::unordered_map<std::pair<..., ...>, ...>

From: Aaron Gray <aaronngray.lists_at_[hidden]>
Date: Mon, 2 Oct 2023 18:45:48 +0100
On Mon, 2 Oct 2023 at 18:39, Aaron Gray <aaronngray.lists_at_[hidden]> wrote:
>
> On Mon, 2 Oct 2023 at 11:30, Bo Persson via Std-Discussion
> <std-discussion_at_[hidden]> wrote:
> >
> > On 2023-10-02 at 11:33, Aaron Gray via Std-Discussion wrote:
> > > I am trying to work out how to do a :-
> > >
> > > std::unordered_map<std::pair<const Type *, const Type*>, bool,
> > > std::hash<Type>> subTypeMemorization;
> > >
> > > Given a barebones class Type :-
> > >
> > > class Type {
> > > public:
> > > std::string name;
> > > ....
> > > };
> > >
> > > Godbolt attempted example :-
> > >
> > > https://godbolt.org/z/r4YrG841E
> > >
> >
> > The hash should not be for 'Type', but for the whole key
> > 'std::pair<const Type *, const Type*>'.
>
> I am more interested in hashing based on the semantics rather than
> pointers or data based constructs.
>
> > And, BTW, doesn't mapping to a bool look very similar to a set?
>
> Its a two dimensional cross product space.

I have a solution to the hashing from Bonita Montero on comp.lang.C++ :-

#include <string>
#include <utility>
#include <unordered_map>
#include <functional>

using namespace std;

struct Type
{
        string name;
};

template<>
struct hash<pair<Type *, Type *>>
{
        size_t operator ()( pair<Type *, Type *> const &key )
        {
                size_t hash = 0;
                hash ^= key.first ? std::hash<string>()( key.first->name ) :
std::hash<void *>()( nullptr );
                hash ^= key.second ? std::hash<string>()( key.second->name ) :
std::hash<void *>()( nullptr );
                return hash;
        }
};

unordered_map<pair<Type *, Type *>, bool> map;

A

Received on 2023-10-02 17:46:06