QT:用QSet儲存自定義結構體的問題——QSet和STL的set是有本質區別的,QSet是基於哈希算法的,要求提供自定義==和qHash函數


前幾天要用QSet作為儲存一個自定義的結構體(就像下面這個程序一樣),結果死活不成功。。。

后來還跑到論壇上問人了,丟臉丟大了。。。

 

事先說明:以下這個例子是錯誤的

 

[cpp]  view plain copy print ?
 
  1. #include <QtCore>  
  2.   
  3. struct node  
  4. {  
  5.     int cx, cy;  
  6.     bool operator < (const node &b) const   
  7.     {  
  8.         return cx < b.cx;  
  9.     }  
  10. };  
  11.   
  12. int main(int argc, char *argv[])  
  13. {  
  14.     QCoreApplication app(argc, argv);  
  15.   
  16.     QSet<node> ss;  
  17.     QSet<node>::iterator iter;  
  18.     node temp;  
  19.     int i, j;  
  20.     for(i=0,j=100;i<101;i++,j--)  
  21.     {  
  22.         temp.cx = i;  
  23.         temp.cy = j;  
  24.         ss.insert(temp);  
  25.     }  
  26.     for(iter=ss.begin();iter!=ss.end();++iter)  
  27.         qDebug() << iter->cx << "  " << iter->cy;  
  28.   
  29.     return 0;  
  30. }  



 

后來經過高手提醒,再經過自己看文檔,才發現QSet和STL的set是有本質區別的,雖然它們的名字很像,前者是基於哈希表的,后者是紅黑樹的變種。。。。


QT文檔中清楚地寫着:In addition, the type must provide operator==(), and there must also be a global qHash() function that returns a hash value for an argument of the key's type. 


簡而言之,就是:
QSet是基於哈希算法的,這就要求自定義的結構體Type必須提供:
1. bool operator == (const Type &b) const
2. 一個全局的uint qHash(Type key)函數

 

廢話說完了,上正確的代碼:

 

[cpp]  view plain copy print ?
 
  1. #include <QtCore>  
  2.   
  3. struct node  
  4. {  
  5.     int cx, cy;  
  6.     bool operator < (const node &b) const   
  7.     {  
  8.         return cx < b.cx;  
  9.     }  
  10.     bool operator == (const node &b) const  
  11.     {  
  12.         return (cx==b.cx && cy==b.cy);  
  13.     }  
  14. };  
  15.   
  16. uint qHash(const node key)  
  17. {  
  18.     return key.cx + key.cy;  
  19. }  
  20.   
  21. int main(int argc, char *argv[])  
  22. {  
  23.     QCoreApplication app(argc, argv);  
  24.   
  25.     QSet<node> ss;  
  26.     QSet<node>::iterator iter;  
  27.     node temp;  
  28.     int i, j;  
  29.     for(i=0,j=100;i<101;i++,j--)  
  30.     {  
  31.         temp.cx = i;  
  32.         temp.cy = j;  
  33.         ss.insert(temp);  
  34.     }  
  35.     for(iter=ss.begin();iter!=ss.end();++iter)  
  36.         qDebug() << iter->cx << "  " << iter->cy;  
  37.   
  38.     return 0;  
  39. }  


以后寫代碼時,一定不能想當然了啊,切記!!!

http://blog.csdn.net/small_qch/article/details/7384966


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM