Search code examples
qtuniqueqlist

How can i make a QList<QVector3D> unique


I have a QList consist of QVector3D. A QVector3D represents a vertex or a point. This List holds also all vertices of a STL-File. The problem is that a vertex exist multiple times in the list. In need a list of the unique vertices of a STL-File. How can i implement it with Qt 5.0.2?


Solution

  • QSet uses a hash-function for ensuring the uniqueness of the value (QMap uses operator <) There is no qHash implementation for QVector3D in Qt. You could implement your own one e.g. as in example:

    //place anywhere in Qt-code
    #include <QSet>
    #include <QVector3D>
    #include <QList>
    
    uint qHash(const QVector3D &v)
    {
        return qHash( QString( "%1x%2x%3" ).arg(v.x()).arg(v.y()).arg(v.z()) ) ;
    }
    
    int foo()
    {
        QList<QVector3D> uvector3D_1;
        QSet<QVector3D> uvector3D_2;
    
        uvector3D_2 = QSet<QVector3D>::fromList(uvector3D_1);
    return 0;
    }
    
    static int testFoo = foo();
    

    Of cause it is not the fastest one, it relies on Qt's function qHash for QString. But I think it's good for demonstration.