我在把一個類的對象在一個無序的地圖如下關鍵 有問題的關鍵是一個簡單的例子:對象無序地圖
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試着插入兩個不同對象和試圖顯示它是顯示分段錯誤..再次,如果我嘗試使用find(),那麼它也顯示分段錯誤..它很難理解爲什麼unordered_map顯示此行爲。
任何幫助將不勝感激!這對我的項目將是一個很大的幫助...
@KO thnks ....只是忘記了... – 2011-04-16 12:02:41