开发者

object as a key of unordered map

开发者 https://www.devze.com 2023-02-25 01:11 出处:网络
I am having problem in putting object of a class in an unordered map as key here is a simple example: class first

I am having problem in putting object of a class in an unordered map as key here is a simple example:

class first
{
        string name;
        public:
        first(){}
        first(string nam):name(nam){}
        string get_name() const
        {
                return name;
        }
};

struct SampleTraits
{
        size_t operator()(const first &that) const
        {
                return tr1::hash<const char*>()(that.get_name().c_str());
        }

        bool operator()(const first &t1,const first &t2) const
        {
                return t1.get_name()==t2.get_name();
        }

};
typedef tr1::unordered_set<unsigned short> uset;
typedef tr1::unordered_map<first,uset,SampleTraits,SampleTraits> umap;

ostream& operator <<(ostream& out, uset &ust)
{
        for(uset::iterator it=ust.begin开发者_C百科();it!=ust.end();++it)
                out<<" "<<*it;
}

int main()
{
        umap *mymap= new umap;
        string names,nm,n;
        cout<<"\nEnter 1st name: ";
        cin>>names;
        first obj(names);
        (*mymap)[obj].insert(100);
        (*mymap)[obj].insert(120);
        (*mymap)[obj].insert(112);

        cout<<"\nEnter 2nd name:";
        cin>>nm;
        first obj2(nm);
        (*mymap)[obj2].insert(201);
        (*mymap)[obj2].insert(202);

        cout<<"\nEnter name which u want to search:";
        cin>>n;

        first obj1(n);
        umap::iterator it=mymap->find(obj1);
        cout<<it->first.get_name();
        cout<<it->second;
        //delete mymap;
        /*
        for(umap::iterator it=mymap->begin();it!=mymap->end();it++)
        {
                cout<<it->first.get_name()<<" ";
                cout<<it->second<<endl;
        }
        */
        return 0;
}

My problem is when iam tryin to insert two different objects and trying to display it is shows segmentation fault.. again if i try to use find() then also it shows segmentation fault.. Its quite hard for me to understand why unordered_map is showing this behavior.

Any help will be appreciated!! This will be a great help for my project...


The problem is with hash function. It does not work as you have expected with pointer types, since it uses a pointer to calculate a hash value instead of its content. Using the std::string fixes the problem.

return tr1::hash<string>()(that.get_name());


Looks like you forgot to return out from operator<< for the uset. Although, most compilers will issue warning for such functions they still have to compile them and running such program will result in undefined behaviour.


ostream& operator <<(ostream & out, uset & ust)
{
    for(uset::iterator it=ust.begin();it!=ust.end();++it)
        out<<" "<<*it;

    return out;
}

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号