3

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 ?

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
artoon
  • 729
  • 2
  • 14
  • 41

2 Answers2

6

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.

vahancho
  • 20,808
  • 3
  • 47
  • 55
0

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 = ...; }
  ...
};
Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313