Iterating over a QMap with for

前端 未结 9 1692
执笔经年
执笔经年 2021-01-31 07:02

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

QMap extensions;
//.. 

for(auto e : extensions)
{
  fou         


        
9条回答
  •  不思量自难忘°
    2021-01-31 07:49

    QMap::iterator uses key() and value() - which can be found easily in the documentation for Qt 4.8 or the documentation for Qt-5.

    Edit:

    A range-based for loop generates codes similar to this (see CPP reference):

    {
        for (auto __begin = extensions.begin(), __end = extensions.end();
                __begin != __end; ++__begin) {
            auto e = *__begin; // <--- this is QMap::iterator::operator*()
            fout << e.first << "," << e.second << '\n';
        }
    } 
    

    QMap::iterator::iterator*() is equivalent to QMap::iterator::value(), and does not give a pair.

    The best way to write this is without range-based for loop:

    auto end = extensions.cend();
    for (auto it = extensions.cbegin(); it != end; ++it)
    {
        std::cout << qPrintable(it.key()) << "," << qPrintable(it.value());
    }
    

提交回复
热议问题