遍历 QHash 并提取重复值的键时遇到问题
trouble iterating over a QHash and extracting duplicate value's keys
我正在尝试使用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(", "));
}
相关文章:
- 编译包含字符串的代码时遇到问题
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 从其他类访问类时遇到问题
- 使用静态成员声明类时遇到问题
- C++ 填充数组时遇到问题
- 在将字符串放入字符串向量时遇到问题?
- 余数除法和不允许除以零 (c++) 时遇到问题
- 我在C++中使用 getline() 函数时遇到问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 在我的四叉树实现中遇到问题
- 在 c++ 中循环遍历数组时遇到问题
- 使用 MinGW 在 Windows 上构建 GLEW 时遇到问题
- 编译 Cilk Plus 程序时遇到问题
- 存储另一个函数返回的布尔数组时遇到问题
- 我在 OpenGL 中显示图像时遇到问题
- 我在解决此错误时遇到问题.我正在努力在主函数中传递数组
- 在 for 循环中更新两个变量时遇到问题C++
- 为什么我的程序在打开网络设备时遇到问题
- 在 Tensorflow C++ 中使用 FIFOQueue 时遇到问题
- 为什么我在虚幻引擎中的多态性和接口方面遇到问题?