遍历 QHash 并提取重复值的键时遇到问题

trouble iterating over a QHash and extracting duplicate value's keys

本文关键字:遇到 问题 QHash 提取 遍历      更新时间:2023-10-16

我正在尝试使用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() 之后,你的迭代器位于第一个(0th)和第二个元素之间,所以如果你的第一个键没有任何重复项,i.findNext(...) 会将 i 留在哈希的末尾,所以 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;
}

由于您正在寻找具有相等"价值"的项目,因此反转键和值的角色将免费为您提供(伪代码):

QHash<QByteArray, QStringList> m_hash;
// fill m_hash 
for(auto fileName : fileNames) {
   m_hash[md5sumForFile(fileName)] << fileName; 
}
// now for each Key of m_hash, the Value is a list of filenames for 
// which md5sum(file contents) equals Key
QStringList results;
for(auto dupes : m_hash) {
    results.append(dupes.join(", "));
}