gpt4 book ai didi

c++ - 如何删除 QStringList 中的冗余元素

转载 作者:行者123 更新时间:2023-11-30 01:41:24 27 4
gpt4 key购买 nike

我正在努力寻找一个安全的解决方案(担心迭代器失效)来删除 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 documentation :

Multiple iterators can be used on the same list. If the list is modified while a QListIterator is active, the QListIterator will continue iterating over the original list, ignoring the modified copy.

但是效率很低,此时最好只使用一些数据结构,比如前缀树。

关于c++ - 如何删除 QStringList 中的冗余元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41292980/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com