How to modify elements of a QSet?

1k Views Asked by At

I have QSet<QuadPattern> texture; and I would like modify all QuadPattern in a loop.

foreach is not the good solution because it makes a copy.

With this code :

QMutableSetIterator<QuadPattern>  it(texture);
while (it.hasNext())
{
    it.next();
    it.value().setCoordinate(...));
}

I get a compilation error :

error: C2662: 'QuadPattern::setCoordinate' : cannot convert 'this' pointer from 'const QuadPattern' to 'QuadPattern &'
Conversion loses qualifiers

The function setCoordinate is like this :

inline void setCoordinate(const std::pair &value) { _coordinate = value; }

Why this error ?

2

There are 2 best solutions below

0
vahancho On BEST ANSWER

Error is because you try to modify the const object returned by the QMutableSetIterator::value() function.

I believe you cannot modify your set's items in that way, and therefore there is no such API. What you need to modify all items is simply clearing the set and inserting new items again.

0
Kuba hasn't forgotten Monica On

There is a good reason for the QMutableSetIterator::value() to return a const reference. The items in a set are internally indexed based on their hash. You generally need to remove and reinsert the item anyway if you wish to change it. If you wish to avoid copying of the data, make your QuadPattern an implicitly shared class:

class QuadPatternData : public QSharedData
{
   ...
};

class QuadPattern {
  QSharedDataPointer<QuadPatternData> d;
public:
  QuadPattern() : d(new QuadPatternData) {}
  QuadPattern(const QuadPattern & other) : d(other.d) {}
  QuadPattern(QuadPattern && other) { d.swap(other.d); }
  void setCoordinate( ... ) { d->coordinate = ...; }
  ...
};