Solved PHP foreach equivalent
-
In PHP we have foreach with a '=>' keyword that translates the key and value into a variable, for example:
$arr = [ 'foo' => [ 'bar', 'biz' ] ]; foreach($arr as $key => $value) { // key = foo // value = array with bar and biz. }
How can I translate this to Qt?
-
-
@Volebab
Or if you're not using C++11, you can use theforeach
macro that Qt defines (if not disabled explicitly):QList<QString> listOfStrings; listOfStrings << "String 1" << "String 2" << "String 3"; foreach (QString string, listOfStrings) { // ... }
-
@SGaist I know that, the question wasn't that, the question as related to translate the key and value using foreach as PHP does. - Your answer and the @kshegunov answer is foreach with values only.
-
What container are you using ?
-
I'm using QHash.
I tried using like this:
for (const auto& kv : iter) { qDebug() << kv; }
But I can't get the key.
-
@Volebab
Just use the regular for loop:typedef QHash<QString, QString> MyHash; MyHash container; for (MyHash::Iterator i = container.begin(), end = container.end(); i != end; i++) { QString key = i.key(), value = i.value(); }
Kind regards.
-
@kshegunov Amazing, thank you.
-
QHash<QString, QString> hash; foreach (auto key, hash.keys()) { qDebug() << hash[key]; }