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

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

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

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

    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)函数

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

    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

  • 相关阅读:
    spring boot 中使用redis session
    关于 JVM 内存的 N 个问题(转)
    在JAVA中记录日志的十个小建议
    spring boot jpa 多数据源配置
    python高性能web框架——Japronto
    毕业 3 年,为何技术能力相差越来越大?——转自阿里技术人生
    如何成为技术大牛——阿里CodeLife
    布式之数据库和缓存双写一致性方案解析(转)
    海量数据存储--分库分表策略详解 (转)
    Linux内核模块简单示例
  • 原文地址:https://www.cnblogs.com/findumars/p/4993533.html
Copyright © 2011-2022 走看看