QT:用QSet储存自定义结构体的问题——QSet和STL的set是有本质区别的,QSet是基于哈希算法的,要求提供自定义==和qHash函数

时间:2023-03-09 22:24:22
QT:用QSet储存自定义结构体的问题——QSet和STL的set是有本质区别的,QSet是基于哈希算法的,要求提供自定义==和qHash函数

前几天要用QSet作为储存一个自定义的结构体(就像下面这个程序一样),结果死活不成功。。。

后来还跑到论坛上问人了,丢脸丢大了。。。

事先说明:以下这个例子是错误的

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

后来经过高手提醒,再经过自己看文档,才发现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)函数

废话说完了,上正确的代码:

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

以后写代码时,一定不能想当然了啊,切记!!!

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