Using Custom Data Type in STL's set or map

Using Custom Data Type in STL's set or map

若有一自定義結構S1,欲插入至 set container 中

   string data;
   int     id;
} S1;
 
set<S1> setContainer;
 
S1 s1;
s1.data = "123";
s1.id = 0;
setContainer.insert(s1);

編譯時將會發生許多錯誤

c:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator <(const class std::multimap<_K,_Ty,_Pr,_A> &,const class std::multimap<_K,_Ty,_Pr,_A> &)' : could not deduce template argument for 'const
class std::multimap<_K,_Ty,_Pr,_A> &' from 'const S1'         c:\program files\microsoft visual studio\vc98\include\functional(86) : while compiling class-template member function 'bool __thiscall std::less<struct S1>::operator ()(const S1 &,const S1 &) const'
c:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator <(const class std::map<_K,_Ty,_Pr,_A> &,const class std::map<_K,_Ty,_Pr,_A> &)' : could not deduce template argument for 'const class std
::map<_K,_Ty,_Pr,_A> &' from 'const S1'         c:\program files\microsoft visual studio\vc98\include\functional(86) : while compiling class-template member function 'bool __thiscall std::less<struct S1>::operator ()(const S1 &,const S1 &) const'
c:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator <(const class std::multiset<_K,_Pr,_A> &,const class std::multiset<_K,_Pr,_A> &)' : could not deduce template argument for 'const class s
td::multiset<_K,_Pr,_A> &' from 'const S1'         c:\program files\microsoft visual studio\vc98\include\functional(86) : while compiling class-template member function 'bool __thiscall std::less<struct S1>::operator ()(const S1 &,const S1 &) const'
c:\program files\microsoft visual studio\vc98\include\functional(86) : error C2784: 'bool __cdecl std::operator <(const class std::set<_K,_Pr,_A> &,const class std::set<_K,_Pr,_A> &)' : could not deduce template argument for 'const class std::set<_K
,_Pr,_A> &' from 'const S1'

 

必須提供給set container 一個 compare function 才能通過編譯

   string  data;
   int     id;
} S1;
 
struct s1_less   {   
  bool operator() (S1   p,S1   q) const   
  {   
  	return (p.data   <  q.data);   
  }   
};
 
set<S1, s1_less> setContainer;
 
S1 s1;
s1.data = "123";
s1.id = 0;
setContainer.insert(s1);

 

Dotblogs 的標籤: ,