Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

The Qt documentation recommend an iterator-based solution to iterate over an associative container like QMap and QHash, and I always wondered if there really isn't a (nice) solution using a foreach loop like in PHP:

foreach($container as $key => $value)

I looked into the source code of the foreach macro and extended it by a key variable. The following code is only the GCC version of the loop (it doesn't work with all compilers, see Q_FOREACH macro definition in qglobal.h for other versions).

#define foreachkv(keyvar, variable, container)                        \
for (QForeachContainer<__typeof__(container)> _container_(container); \
     !_container_.brk && _container_.i != _container_.e;              \
     __extension__  ({ ++_container_.brk; ++_container_.i; }))        \
    for (keyvar = _container_.i.key();; __extension__ ({break;}))     \
        for (variable = *_container_.i;; __extension__ ({--_container_.brk; break;}))

Now you can do the following:

QVariantHash m;
m.insert("test", 42);
m.insert("foo", true);
foreachkv(QString k, QVariant v, m)
    qDebug() << k << "=>" << v;

The output will be:

"foo" => QVariant(bool, true) 
"test" => QVariant(int, 42)

Tests I've done so far:

  • examples from above
  • foreachkv works as expected with break and continue statements within the loop.

What did I do? I just added another for loop to introduce the key variable (called keyvar in the macro). Maybe I don't need this loop?

share|improve this question

migrated from stackoverflow.com May 11 '12 at 12:46

This question came from our site for professional and enthusiast programmers.

    
Actually I think the best place would be qt-project.org/contribute. It would definitely be useful for code clarity. –  Styne666 May 9 '12 at 21:31
    
AFAIK, Qt is no longer interested in improving the C++ API. They fully concentrate on QML / QtQuick now. –  leemes May 9 '12 at 22:21

1 Answer 1

up vote 2 down vote accepted

You can probably do something simpler to avoid making this a special case macro, e.g. using std::tie or boost::tie if that's not available:

#include <map>
#include <functional>
#include <boost/foreach.hpp>
#include <iostream>

int main() {
  std::map<int, std::string> map = {std::make_pair(1,"one"), std::make_pair(2,"two")};
  int k;
  std::string v;
  BOOST_FOREACH(std::tie(k, v), map) {
    std::cout << "k=" << k << " - " << v << std::endl;
  }
}
share|improve this answer
1  
If you’ve got std::tie then you also have range-based for. –  Konrad Rudolph Jun 23 '12 at 12:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.