如何删除 QStringList 中的冗余元素

How to remove redundant elements in a QStringList

本文关键字:冗余 元素 QStringList 何删除 删除      更新时间:2023-10-16

我正在努力找到一个安全的解决方案(害怕迭代器失效)来擦除QStringList中的一些元素:

static QStringList s_listDistantDirs;

我想擦除一个元素CurrentElement如果它的长度优于另一个元素OtherElement并且OtherElement等于CurrentElement.mid(OtherElement.length()).

换句话说,我想擦除列表中现有目录的子目录。

我尝试使用QMutableListIterator<QString>但不知道如何正确使用它来嵌套循环。

你可能想要这样的东西:

static QStringList s_listDistantDirs;
//...
QStringListIterator it(s_listDistantDirs);
while (it.hasNext()) {
QString& otherElement = it.next().value();
// QMutableStringListIterator is just a typedef for QMutableIterator<QString>
QMutableStringListIterator mit(s_listDistantDirs);
while(mit.hasNext()) {
QString& currentElement = mit.next().value();
if (currentElement.length() > otherElement.length()
&& currentElement.startsWith(otherElement))
mit.remove(); // this will not invalidate `it`!
}
}

根据Qt文档:

可以在同一列表中使用多个迭代器。如果在 QListIterator 处于活动状态时修改了列表,则 QListIterator 将继续循环访问原始列表,忽略修改后的副本。

但是它的效率很低,在这一点上,最好只使用一些数据结构,例如前缀树。

换句话说,我想删除列表中现有目录的子目录。

如果事先知道现有的目录,你可以使用 QStringList::filter() 和像这样的正则表达式:

#include <QtCore>
#include <QRegularExpression>
#include <QStringList>
#include <QDebug>
int main() {
QString myPath("/my/path/");
QRegularExpression re("^(?!" + myPath + ")");
QStringList list = (QStringList()
<< "/my/path/a"
<< "/my/path/b"
<< "/some/other/path/c"
<< "/my/path/d");
for(auto &l: list.filter(re)) {
qDebug() << l;
}
}