1

ここでのキーは簡単な例であるため、クラスのオブジェクトを順序付けられていないマップに配置する際に問題が発生します。

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

私の問題は、iam tryinが2つの異なるオブジェクトを挿入して表示しようとすると、セグメンテーション違反が表示されることです。再びfind()を使用しようとすると、セグメンテーション違反も表示されます。unordered_mapが表示される理由を理解するのは非常に困難です。この動作。

どんな助けでも大歓迎です!! これは私のプロジェクトにとって大きな助けになるでしょう...

4

2 に答える 2

4

問題はハッシュ関数にあります。コンテンツの代わりにポインターを使用してハッシュ値を計算するため、ポインター型では期待どおりに機能しません。std::string を使用すると問題が解決します。

return tr1::hash<string>()(that.get_name());
于 2011-04-16T10:13:58.933 に答える
0

usetのoperator<<から戻るのを忘れたようです。ただし、ほとんどのコンパイラはそのような関数に対して警告を発行しますが、それでもそれらをコンパイルする必要があり、そのようなプログラムを実行すると未定義の動作が発生します。


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

    return out;
}

于 2011-04-16T08:46:08.437 に答える