user389955
user389955

Reputation: 10457

cannot contain user defined class in hash_set

I am implementing six degree Kevin Bacon problem and writing a class for the actor node. I can use set but not hash_set container to hold a user defined class. why? the error msg shows:error C2440: 'type cast' : cannot convert from 'const ActorGraphNode' to 'size_t' 1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called....

#include <hash_set>
#include <set>
class ActorGraphNode{
    public: 
    string ActorName;
    //hash_set<ActorGraphNode> linkedActors;
    set<ActorGraphNode> linkedActors;
    ActorGraphNode(string name):ActorName(name){}
    void linkCostar(ActorGraphNode actor){
       linkedActors.insert(actor);
       actor.linkedActors.insert(*this);
    }
    bool operator<( const ActorGraphNode& a ) const
    { return ActorName < a.ActorName ? true : false;}
};

Upvotes: 0

Views: 184

Answers (2)

riv
riv

Reputation: 7324

Unsurprisingly, hash_set requires you to implement a hash function for your type.

class ActorGraphNode{
    public: 
    string ActorName;
    hash_set<ActorGraphNode> linkedActors;
    //set<ActorGraphNode> linkedActors;
    ActorGraphNode(string name):ActorName(name){}
    void linkCostar(ActorGraphNode actor){
       linkedActors.insert(actor);
       actor.linkedActors.insert(*this);
    }
    bool operator<( const ActorGraphNode& a ) const
    { return ActorName < a.ActorName;}
    bool operator ==( const ActorGraphNode& a ) const
    { return ActorName == a.ActorName;}
    operator size_t() const
    {
      return hash<string>()(ActorName);
    }
};

Upvotes: 1

user389955
user389955

Reputation: 10457

thanks all for ur answers and comments. Here is my updated code with your help. plus for function linkCostar() I use pass by reference now:

class ActorGraphNode{
public: 
    string ActorName;
    hash_set<ActorGraphNode> linkedActors;
    ActorGraphNode(string name):ActorName(name){}
    void linkCostar(ActorGraphNode& actor){
        linkedActors.insert(actor);
        actor.linkedActors.insert(*this);
    }
    bool operator==( const ActorGraphNode& a ) const
    { return ActorName == a.ActorName ? true : false;}
    operator size_t() const
    {
        const int HASHSIZE = 501;
        int seed = 131;
        size_t sum = 0;
        for(size_t i = 0; i < ActorName.length(); ++i) 
            sum = (sum * seed) + ActorName[i];      
        return sum % HASHSIZE;
    }
};

Upvotes: 0

Related Questions