比较 list<string> 和 vector<string> 中的字符串元素

Posted

技术标签:

【中文标题】比较 list<string> 和 vector<string> 中的字符串元素【英文标题】:Comparing string elements in list<string> and vector<string> 【发布时间】:2014-09-21 09:51:05 【问题描述】:

我想比较list&lt;string&gt;vector&lt;string&gt;中的字符串元素。

这样的代码可以正常工作:

list<string> FileNamesPatternsList; // In this list there are about 100 files
vector<string> FilesToBeSearched;   // In this vector there are about 300 files

list<string>::iterator compareIterator;
vector<string>::iterator compareIterator2;

for( compareIterator = FileNamesPatternsList.begin(); compareIterator != FileNamesPatternsList.end(); compareIterator++)
for( compareIterator2 = FilesToBeSearched.begin(); compareIterator2 != FilesToBeSearched.end(); compareIterator2++)
            
                smatch result;
                if(regex_search(*compareIterator2,result,regex(*compareIterator)))
                MyFilewithResults << "File: " << result[0] << "fit to" << *compareIterator2 << endl;
                
            

    

虽然结果只有匹配的元素存储到 txt 文件 (MyFilewithResults)。

如何存储不匹配的结果?添加if()...else 在这种情况下不起作用。

【问题讨论】:

模式是否列出了实际的正则表达式,或者它们只是两个字符串容器并且您正在尝试计算差异? 您需要有一个变量来告诉您是否在内循环中找到了匹配项。如果没有找到匹配项,则在该循环之外记录结果。 @WhozCraig:两个容器都只是字符串,我正在尝试使用 regex_search 比较它们(成功的比较工作正常,但我也想捕获那些不匹配的文件)。列表容器是使用 sort() 和 unique() 函数 我知道它们是字符串,但FileNamePatternsList 中的字符串是实际的正则表达式(模式、捕获等)还是仅仅是字符串?如果它只是绳子与绳子,那么您正在使用大锤来拍打苍蝇。也许对序列进行排序(或保持排序)并改用std::set_difference FileNamePatternsList 是正则表达式的列表,例如uniqufile.bin 当向量是例如01_uniquefile.bin,第二个_uniquefile.bin。和 uniquefile.gz。我需要找到所有适合模式的字符串(这有效),但也需要那些不适合的字符串(这是我的问题寻求帮助) 【参考方案1】:

听起来解决方案是“记住”找到匹配项。

所以,在伪代码中:

for(every element)

  found = false
  for(each thing to match with)
  
    if (is a match)
    
       found = true;
       ... do other stuff here ... 
    
  
  if (!found)
  
     ... do whatever you do if it wasn't in the list ...
  

【讨论】:

以上是关于比较 list<string> 和 vector<string> 中的字符串元素的主要内容,如果未能解决你的问题,请参考以下文章

两个list比较相等元素

MultiMapBidiMap及LazyMap的使用

C# list<string> 中的项怎么比较是不是一致?

string类和vector<char>的区别,vector和list比较

java list三种遍历方法性能比较

比较两个Excle表格的修改内容