c++qtset

QSet intersection without losing elements


How to take an intersection between 2 QSets where the first does not lose elements, but just the resulting intersection is returned?

The reason is that I am trying to perform many intersections with some sets, but had to find out the hard way that the elements were lost in the process.

QSet<int> a, b;
a.insert(1);
a.insert(2);         // { 1, 2 }
b.insert(1);         // { 1 }
a.intersection(b);   // { 1 }  
a                    // { 1 }

Solution

  • intersect modifies the set you apply it to. If you don't want to do that, don't use intersect.

    The overloaded operator& returns a new QSet that's the intersection of two QSets. There's also an assignment operator operator&=.

    QSet is hash-based. If you're working with sets of small integers and you're concerned with efficiency, QBitArray might work better.