Since Qt 5.10 you can use a simple wrapper class to use a range based for loop, but still be able to access both the key and value of the map entries.
Put the following code somewhere at the top of your source file or in a header that you include:
template<class K,class V>
struct QMapWrapper {
const QMap<K,V> map;
QMapWrapper(const QMap<K,V>& map) : map(map) {}
auto begin() { return map.keyValueBegin(); }
auto end() { return map.keyValueEnd(); }
};
To iterate over all entries you can simply write:
QMap<QString, QString> extensions;
//..
for(auto e : QMapWrapper(extensions))
{
fout << e.first << "," << e.second << '\n';
}
The type of e
will be std::pair<const QString&, const QString&>
as is partially specified in the QKeyValueIterator documentation.
The member variable map
is an implicitly shared copy of the map, to avoid a segmentation fault in case this is used with temporary values. Hence as long as you do not modify the map within the loop, this only has a small constant overhead.
The above example uses class template argument deduction, which was introduced in C++17. If you're using an older standard, the template parameters for QMapWrapper must be specified when calling the constructor. In this case a factory method might be useful:
template<class K,class V>
QMapWrapper<K,V> wrapQMap(const QMap<K,V>& map) {
return QMapWrapper<K,V>(map);
}
This is used as:
for(auto e : wrapQMap(extensions))
{
fout << e.first << "," << e.second << '\n';
}