Search code examples
c++qtqt4comparisonqmap

QSet in QMap or QHash


I have QMap and I want to make QSet the key of it, I couldn't do that because QSet is not comparable. for example:

QSet<int> intSet;
QMap<QSet<int>, char> charSet;

intSet.insert(1);
intSet.insert(2);
intSet.insert(3);

charSet.insert(intSet, '6');

Is there any way to make it work? and if I inherit from QSet and define operator < how should I implement it? i.e: What should be the logic of the comparison?

Note: I care too much about performance


Solution

  • You seem to know how to make it work: define an operator<(const QSet<int>&) function (I don't believe Qt requires that you subclass QSet to make this work, I know STL does not).

    Obviously, implementing a comparator on an unordered set is going to be difficult. And doing it such that it runs in constant time is, I believe, impossible. You might try something like checking the size first, and then sorting and comparing the two contents as lists.

    But broadly: don't do this. It's an abuse. Surely there is something you can use for the key of your set that is not a mutable data structure. Is the space of integers in the sets fixed and small (i.e. always in the range 0-1024 or whatnot)? Then try a bitmask stored in a QByteArray. etc...