对象作为无序映射的键 [英] object as a key of unordered map

查看:23
本文介绍了对象作为无序映射的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将类的对象放在无序映射中作为键时遇到问题这是一个简单的例子:

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();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;
}

我的问题是当我尝试插入两个不同的对象并尝试显示它时显示分段错误..如果我再次尝试使用 find() 然后它也显示分段错误..我很难理解为什么unordered_map 显示了这种行为.

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...

推荐答案

问题在于散列函数.对于指针类型,它不能像您预期的那样工作,因为它使用指针来计算散列值而不是其内容.使用 std::string 可以解决问题.

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());

这篇关于对象作为无序映射的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆