user2094257
user2094257

Reputation: 1715

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

I am trying to iterate over a QHash using a QMutableHashIterator and find all duplicate values and then add each duplicate value's key to a QStringList. i've never used a QHash before and not sure exactly how to go about this. I don't get any output with my code at this stage... Any idea what I am doing wrong?

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;
}

Upvotes: 0

Views: 1422

Answers (2)

aah
aah

Reputation: 91

Is the intent to remove all the items from the list (since you loop until m_hash is empty...)? This code should not return on a non-empty hash to begin with.
Qt uses Java style iterators (http://doc.qt.io/qt-5/qmutablehashiterator.html). After your first i.next(), your iterator is positioned between the first (0th) and second elements, so if your first key does not have any duplicates, i.findNext(...) will leave i at the end of the hash, so i.hasNext() should constantly return false.

You would want something like:

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;
}

Upvotes: 1

arhzu
arhzu

Reputation: 570

Since you are looking for items with equal "value", reversing the roles of key and value would give it to you for free (pseudocode):

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(", "));
}

Upvotes: 0

Related Questions