2011-09-07 177 views
1

我有两个列表。两者都含有相同的价值观:QString :: startWith()&QStringList :: removeAll()不像预期的那样运行

QStringList filePaths; 
filePaths.append("C:/backup"); 
filePaths.append("C:/download/file1"); 
filePaths.append("D:"); 
filePaths.append("C:/program"); 
filePaths.append("C:/download"); 

QStringList refinedPaths; 

int size = filePaths.size(); 

for(int i = 0; i < size; i++) 
{ 
    refinedPaths.append(filePaths.at(i)); 
} 

for(int i = 0; i < size; i++) 
{ 
    QString str1 = filePaths.at(i); 

    for(int j = 0; j < size; j++) 
    { 
    QString str2 = filePaths.at(j); 

    if(str2 == str1) 
    { 
     continue; 
    } 

    if(str2.startsWith(str1)) 
    { 
     refinedPaths.removeAll(str2); 
    } 
    } 
} 

我很期待出现的情况是: *遍历字符串列表,每一个项目相互的列表进行比较。 *如果string1以string2开头(因此string2是string1的父目录) *从'精致'字串列表中移除该字串。

Howver,正在发生的事情是,if(str2.startsWith(str1))每次都返回true,并refinedPaths.removeAll(str2);不删除列表中的任何字符串。

任何想法?

回答

1

你的代码工作正常,不知道你指的是什么问题。这里使用您的代码我

C:/backup 
D: 
C:/program 
C:/download 

有几件事情,以改善输出,

  1. ,而不是通过元素,你可以只使用拷贝构造函数,即以复制文件路径到refinedPaths QStringList refinedPaths(filePaths);

    复制QStringList中元素
  2. 使用迭代器而不是按size()进行迭代。

    QStringList refinedPaths(filePaths); 
    
    for(QStringList::const_iterator itr1 = filePaths.begin(); filePaths.end() != itr1 ; ++itr1) 
    { 
    
        for(QStringList::const_iterator itr2 = filePaths.begin(); filePaths.end() != itr2 ; ++itr2) 
        { 
        if(*itr1 == *itr2) 
        { 
         continue; 
        } 
    
        if(itr2->startsWith(*itr1)) 
        { 
         refinedPaths.removeAll(*itr2); 
        } 
        } 
    } 
    
+0

我可以看到现在的代码工作更快 - 我觉得在QtCreator的调试模式中的变量不同时里面一个for循环更新,或一些东西。为什么你建议使用迭代器来处理我所做的事情? – nf313743

+0

对于一般列表.size()操作是O(n),但QStringLists是使用arrayLists实现的,size()操作是O(1)我相信。迭代器尽量减少了越界错误的可能性,大多数现有的算法都使用迭代器作为输入。更详细的答案在这里:http://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices – blueskin

2

下面的代码片段根据需要使列表合理化。

foreach (const QString& path, filePaths) 
    { 
     foreach (const QString& other, filePaths) 
     { 
     if (other != path && other.startsWith(path)) 
      filePaths.removeOne (other); 
     } 
    } 
0
filePaths.sort(); 
    for (int k = 0; k < filePaths.size();) 
    { 
     const QString & path = filePaths[k]; 
     while(k+1 < filePaths.size() && filePaths.at(k+1).startsWith(path)) 
      filePaths.removeAt(k+1); 
     k++; 
    } 

约3次给定的数据

相关问题