QList<QString> list {"a", "b", "c", "d"}; QList<QString>::const_iterator citer = list.cbegin(); for (; citer != list.cend(); ++citer) qDebug() << (*citer);
QList<QString> list {"a", "b", "c", "d"}; foreach (QString s, list) qDebug() << s;
QListIterator<QString> iter(list); while(iter.hasNext()) qDebug() << iter.next();
#define Q_FOREACH(variable, container) for (QForeachContainer<__typeof__(container)> _container_(container); !_container_.brk && _container_.i != _container_.e; __extension__ ({ ++_container_.brk; ++_container_.i; })) for (variable = *_container_.i;; __extension__ ({--_container_.brk; break;})) template <typename T> class QForeachContainer { public: inline QForeachContainer(const T& t) : c(t), brk(0), i(c.begin()), e(c.end()) { } const T c; // 将容器标识为 const 不可修改 int brk; typename T::const_iterator i, e; };
for (QString s : list) qDebug() << s;如果变量类型较长,可以使用auto来让编译器自动推断,如下:
for (auto s : list) qDebug() << s;
for (auto &s : list) s = "x";
原文地址:http://blog.csdn.net/xiaohui_hubei/article/details/38401487