QSet with custom compare functor



  • Hi,

    is there any way to define custom compare functor for QSet? For std::set we can define

    std::set<MemoryLayoutInfo,MemoryLayoutInfo::Compare> set;

    and the same for std::unordered set but in documentation about QSet class I didnt see similar constructor so... this class does not support this feature?



  • From the docs:

    "QSet's value data type must be an assignable data type. You cannot, for example, store a QWidget as a value; instead, store a QWidget *. 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. See the QHash documentation for a list of types supported by qHash()."

    If you look at QHash docs there are examples of how to implement this custom qHash.

    http://doc.qt.io/qt-5/qhash.html



  • I read about qHash but I do not understand how this can help me to reorder items in QSet in custom way? qHash is not the same as compare function.

    For example using std::set I can implement custom comparator like below

    class Compare {
        public:
            bool operator()(const MemoryLayoutInfo &x,const MemoryLayoutInfo &y) {
                return x.bits < y.bits ? true  :
                       x.bits > y.bits ? false :
                       x.data <= y.data  ? true  : false;
            }
        };
    


  • From the docs:

    "QSet<T> is one of Qt's generic container classes. It stores values in an unspecified order and provides very fast lookup of the values." So no ordering.

    Do you need to use a Qt container? If not, std::set<T> is ordered. (std::unordered_set<T> is unordered)

    I'm unsure what's the best Qt approach for a ordered container. QMap is ordered by key, but that seems like overkill for the job.


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    From what you wrote QSet is not the class you want to use since as @BjornW already took from the documentation, it's an unordered container.

    There's no equivalent of std::set in Qt. QSet matches std::unordered_set.

    You can find a good analysis of Qt's containers here.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.