Iterating over a QMap with for

user336635 picture user336635 · Dec 15, 2011 · Viewed 82k times · Source

I've a QMap object and I am trying to write its content to a file.

QMap<QString, QString> extensions;
//.. 

for(auto e : extensions)
{
  fout << e.first << "," << e.second << '\n';
}  

Why do I get: error: 'class QString' has no member named 'first' nor 'second'

Is e not of type QPair?

Answer

Arlen picture Arlen · Dec 16, 2011

If you want the STL style with first and second, do this:

for(auto e : extensions.toStdMap())
{
  fout << e.first << "," << e.second << '\n';
}

If you want to use what Qt offers, do this:

for(auto e : extensions.keys())
{
  fout << e << "," << extensions.value(e) << '\n';
}