artoon
artoon

Reputation: 739

How to modify elements of a QSet?

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 ?

Upvotes: 3

Views: 1121

Answers (2)

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 = ...; }
  ...
};

Upvotes: 0

vahancho
vahancho

Reputation: 21230

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.

Upvotes: 6

Related Questions