problem with QHash
-
Hello everybody,
I have a problem when I compile this code :
QHash<QString, double> hash ( it.parameters() ); for(const auto &h : hash) { if(h.key() == "value1") { qDebug() << h.value() ; } }
the compilator return : erreur : request for member ‘key’ in ‘h’, which is of non-class type ‘const double’
and erreur : request for member ‘value’ in ‘h’, which is of non-class type ‘const double’
However the key() return the first element so a QString. So what is the problem and how to fix itthanks for your help
-
@cosmoff said in problem with QHash:
qDebug() << h.value() ;
"h" is your value, a double. It is not the hash.
So write this instead:
qDebug() << hash.value(h) ;
This will print the value for given key (h).
Also, make
hash
const or useqAsConst()
otherwise it will detach in ranged for loop == worse performance. -
@cosmoff said in problem with QHash:
qDebug() << h.value() ;
"h" is your value, a double. It is not the hash.
So write this instead:
qDebug() << hash.value(h) ;
This will print the value for given key (h).
Also, make
hash
const or useqAsConst()
otherwise it will detach in ranged for loop == worse performance. -
Then you need to use iterators - Qt's containers return the value in a range-based for loop:
for (auto it = hash.cbegin(); it != hash.cend(); ++it) qDebug() << it.key() << it.value();
-
In fact, I want to read all the elements key and value of my loop, like :
for(const auto &h : hash) { qDebug() << h.hey() << h.value(); }
@cosmoff
directly taken from the docs:QHashIterator<QString, int> i(hash); while (i.hasNext()) { i.next(); cout << i.key() << ": " << i.value() << endl; } //std style QHash<QString, int>::const_iterator i = hash.constBegin(); while (i != hash.constEnd()) { cout << i.key() << ": " << i.value() << endl; ++i; }
-
@cosmoff
directly taken from the docs:QHashIterator<QString, int> i(hash); while (i.hasNext()) { i.next(); cout << i.key() << ": " << i.value() << endl; } //std style QHash<QString, int>::const_iterator i = hash.constBegin(); while (i != hash.constEnd()) { cout << i.key() << ": " << i.value() << endl; ++i; }
-
@cosmoff Then please mark this topic as solved, thx.