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

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

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

代码如下:

#include    
struct node  
{  
    int cx, cy;  
    bool operator < (const node &b) const   
    {  
        return cx < b.cx;  
    }  
};  
  
int main(int argc, char *argv[])  
{  
    QCoreApplication app(argc, argv);  
  
    QSet ss;  
    QSet::iterator iter;  
    node temp;  
    int i, j;  
    for(i=0,j=100;i<101;i++,j--)  
    {  
        temp.cx = i;  
        temp.cy = j;  
        ss.insert(temp);  
    }  
    for(iter=ss.begin();iter!=ss.end();++iter)  
        qDebug() << iter->cx << "  " << iter->cy;  
  
    return 0;  
}


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


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

#include   
  
struct node  
{  
    int cx, cy;  
    bool operator < (const node &b) const   
    {  
        return cx < b.cx;  
    }  
    bool operator == (const node &b) const  
    {  
        return (cx==b.cx && cy==b.cy);  
    }  
};  
  
uint qHash(const node key)  
{  
    return key.cx + key.cy;  
}  
  
int main(int argc, char *argv[])  
{  
    QCoreApplication app(argc, argv);  
  
    QSet ss;  
    QSet::iterator iter;  
    node temp;  
    int i, j;  
    for(i=0,j=100;i<101;i++,j--)  
    {  
        temp.cx = i;  
        temp.cy = j;  
        ss.insert(temp);  
    }  
    for(iter=ss.begin();iter!=ss.end();++iter)  
        qDebug() << iter->cx << "  " << iter->cy;  
  
    return 0;  
}


上述对Qt QSet与标准模板库中Set简单比较。