比较2 c ++ std :: lists的最快方法,在每次迭代中进行更改

时间:2015-05-28 23:42:02

标签: c++

假设我有2个std :: lists,每个包含不同数量的元素。每个元素(在每个列表上)都具有UNIQUE int id值。在每次迭代中,我需要从第一个列表中删除第二个中没有出现的元素,并从第二个列表中添加不属于第一个列表的元素。例如(数字=唯一ID):

  
      
  1. 迭代:第一[3,2,1],第二[4,3,5,7,6],结果:[3,4,5,6,7]
  2.   
  3. 迭代:第一次[3,4,5,6,7],第二次[4,10,9],结果:[4,10,9]
  4.   

...等 我不能简单地将第二个交换到第一个(让我们认识到它是不可能的,太长时间阅读)。我的问题是: 更新第一个列表可以执行的最佳搜索算法是什么?我的意思是,我应该在两个排序列表上使用嵌套循环并比较ID吗?从第一个缺少的元素中连续删除元素,但首先删除重复的元素。合并吗?或者也许将其中一个unordered_map(哈希表)?

编辑:

我想简化问题,但事实上,现在还不清楚。我无法更改容器,有2个未分类的列表,每个包含2个不同的结构。两种结构之间的唯一链接是id参数。在每次迭代中,我都要检查第一个列表是否与第二个列表相似。 Ids是独一无二的,不允许重复。因此,如果id匹配列表将是相同的。我不能交换它们,因为第一个列表有30个值,第二个列表10个(它没有完成)。还有另一个特殊功能来为第一个列表准备结构,该结构由许多不同的结构组成(包括列表2中的结构)。仅当第二个列表中的ID未出现在第一个列表中时,才会启动这些功能。我不能操纵第一个列表,但我可以修改第二个列表。

我试过这种方式。在每次迭代中:

1. Create a std::unordered_set with hashed ids from second list. Then compare it to first list and remove outdated ids from first list. Remove also repeating ids from unordered_set. We'll end up with the set of new structures from list 2. We can run another functions and then add suitable ones to first list.

2. Sort list2 by ids. Then do binary search.

3. Linear search. 2 loops. Id that appears in first list and doesn't in the second one is removed from first list. Id that appears in both lists is removed from the second list. And finally we got ids that appear in second list and don't in the second one. We can process them and merge with list 1.

最重要的是:会有很多比较,但大多数时候列表都是一样的!

1 个答案:

答案 0 :(得分:1)

最有效的方法可能是简单地将第二个列表分配给第一个:

first = second;

将复制第二个中的所有元素并将它们放在第一个元素中。

如果出于某种原因需要保留元素,可以对每个列表进行排序,并使用set_difference算法查找一个列表中不在另一个列表中的所有元素。