如何删除 QStringList 中的冗余元素
How to remove redundant elements in a QStringList
我正在努力找到一个安全的解决方案(害怕迭代器失效)来擦除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;
}
}
相关文章:
- 如何擦除冗余输入?
- 使用提升几何缓冲区缩放多边形时的冗余折点
- 我应该担心冗余声明吗?
- Qt的slot(?)将冗余命名空间插入连接
- 方法冗余移动调用的移动语义
- 使用 llvm 和本地值编号算法擦除冗余表达式
- 优化堆上创建的冗余变量
- 如何消除访客模式冗余?
- 表达式模板需要冗余重载
- C++,处理多个构造函数重载和冗余代码
- 使用模板基类消除工厂类派生类冗余的干净方法
- 连接两个文件时如何避免冗余尾随换行符?
- CMake:修改共享库时的冗余链接
- 提升精神 X3:"属性没有预期的大小"冗余
- 如何简化此冗余C++代码?
- 是``if`语句''在modulo之前和分配操作之前的冗余
- 使用最终类说明符时,最终函数说明符是否冗余?
- 简化冗余std :: array初始化,当时没有constexpr构造函数
- 尝试使用 OpenMP 并行化递归函数的冗余计算
- 如何删除 QStringList 中的冗余元素