QHash, how to update value in map?
-
I have an instance of QHasp:
typedef QHash<QString, quint64> tProgressMap;
In a class:
tProgressMap mhmTrainees;
In the method that updates progress:
tProgressMap::iterator itFound(mhmpTrainees.find(crstrTrainee)); if ( itFound == mhmpTrainees.end() ) { itFound = mhmTrainees.insert(crstrTrainee, uint64Value); } else { itFound.value() = uint64Value; }
Whilst:
itFound.value() = uint64Value;
Updates the value because value() returns a reference, it does not update the same entry in the mhmpTrainees.
Is there a way to do this or do I have to remove and reinsert?
-
@ollarch , can you show a demonstration please?
Tried:
mhmTrainees[itFound] = uint64Value;
Compile errors:
C2679: binary '[': no operator found which takes a right-hand of type 'QHash<QString, quint64>::iterator'
Edit...
mhmTrainees[itFound.key()] = uint64Value;
This works!
-
@SPlatten
I'm not a wiz with iterators, but you should be able to do it from the right iterator (without having to re-look-up the key). See https://doc.qt.io/qt-5/qhash-iterator.html#detailsLet's see a few examples of things we can do with a QHash::iterator that we cannot do with a QHash::const_iterator. Here's an example that increments every value stored in the QHash by 2:
QHash<QString, int>::iterator i; for (i = hash.begin(); i != hash.end(); ++i) i.value() += 2;
-
@SPlatten said in QHash, how to update value in map?:
the problem is that the iterator itself is not a pointer or a reference so there is no link to the original data source it references, I've resolved this now.
the iterator holds a reference to the item (key and value)!
The code given by @JonB is the right way to do (cf. https://doc.qt.io/qt-5/qhash-iterator.html#details)
mhmTrainees[itFound.key()] = uint64Value;
should beitFound.value() = uint64Value;
-
@KroMignon , that was exactly what my original code looked like and it doesn't work, I can see whilst the iterator is modified the original value in the QHash isn't modified and I'm not surprised because .begin() doesn't return a reference it just returns an iterator so there is no link.
-
@SPlatten said in QHash, how to update value in map?:
begin() doesn't return a reference it just returns an iterator so there is no link
As already said by @KroMignon the iterator holds the reference...
It is also shown in https://doc.qt.io/qt-5/qhash-iterator.html -
-
@SPlatten said in QHash, how to update value in map?:
don't apologise, this isn't what I am seeing in Qt Creator / Debugger.
I am very surprised!
I always do it like this (it.value() = newValue
) and it is the way it is documented.
Can you show how you have set the iterator?
It is an iterator or const_iterator?