c++ - 迭代 QHash 和提取重复值的键时遇到问题

标签 c++ qt

我正在尝试使用 QMutableHashIterator 遍历 QHash 并找到所有重复值,然后将每个重复值的键添加到 QStringList。我以前从未使用过 QHash,也不确定具体如何去做。在这个阶段我的代码没有得到任何输出...知道我做错了什么吗?

QStringList FileChecker::getDuplicateList() {
    QStringList tempList;
    QString tempStr;
    QString currentKey;
    QByteArray currentValue;
    QMutableHashIterator<QString, QByteArray> i(m_hash);


    do {
        while (i.hasNext()) {
            i.next();
            currentKey = i.key();
            currentValue = i.value();

            while (i.findNext(currentValue)){
                tempStr.append(currentKey);
                tempStr.append(i.key());
                i.remove();
        }
        tempList.append(tempStr);
        tempStr.clear();
        }

    } while (m_hash.size() > 0);

    return tempList;
}

最佳答案

是否打算从列表中删除所有项目(因为您循环直到 m_hash 为空...)?此代码不应以非空哈希开头返回。
Qt 使用 Java 风格的迭代器 (http://doc.qt.io/qt-5/qmutablehashiterator.html)。在你的第一个 i.next() 之后,你的迭代器位于第一个(第 0 个)和第二个元素之间,所以如果你的第一个键没有任何重复项,i.findNext(...) 将把 i 留在最后hash,因此 i.hasNext() 应该不断返回 false。

你会想要这样的东西:

QStringList FileChecker::getDuplicateList() {
    QStringList tempList;
    QString tempStr;
    QString currentKey;
    QByteArray currentValue;
    QMutableHashIterator<QString, QByteArray> i(m_hash);


    while (m_hash.size() > 0)
    {
       i.toFront();
       i.next();
       currentKey = i.key();
       currentValue = i.value();
       i.remove();

       while (i.findNext(currentValue)){
            tempStr += i.key() + " ";
            i.remove();
       }
       tempList.append(tempStr);
       tempStr.clear();

    } 

    return tempList;
}

关于c++ - 迭代 QHash 和提取重复值的键时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37599590/

相关文章:

c++ - 指向成员变量的指针与通过指针传递

c++ - 标准如何支持在基类 S 中调用纯虚函数?

c++ - 将 lambda 表达式或函数保存到二进制文件

c++ - DefWindowProc() 问题

c++ - Qt 找不到插槽

c++ - 在 QTextEdit 中更改文本

c++ - 无法在 Windows 上将 SDL 与 MinGW 一起使用

c++ - "this"指针变为空 c++

c++ - bool 值未更改

user-interface - 如何设置QFileDialog来设置初始选择的文件?