比较两个c++ std::列表的最快方式,在每次迭代中更改

Fastest way to compare 2 c++ std::lists, changing in each iteration

本文关键字:方式 迭代 两个 c++ 比较 列表 std      更新时间:2023-10-16

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

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

等等……我不能简单地把第二个换成第一个(让我们认识到这是不可能的,太长了,读不懂)。我的问题是:更新第一个列表的最佳搜索算法是什么?我的意思是,我应该在两个排序列表上使用嵌套循环并比较id吗?从第一个元素中删除第二个元素中缺少的连续元素,同时删除第一个元素中重复的元素。然后合并?或者将其中一个设置为unordered_map(哈希表)?

编辑:

我想简化这个问题,但事实上,现在还不清楚。我不能改变容器,有2个未排序的列表包含2个不同的结构。两种结构之间唯一的联系是一个id参数。在每次迭代中,我都必须检查第一个列表是否与第二个列表相同。id是唯一的,不允许重复。所以如果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.

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

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

first = second;

,它将复制第二个元素并把它们放在第一个。

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