[英]Find if std::list contains element from another std::list
I have two lists:我有两个清单:
std::list<MyClass1> listClass1;
std::list<MyClass2> listClass2;
For sake of simplicity lets say that they have these elements:为简单起见,假设它们具有以下元素:
listClass1
{id: 1, name: "Test1"}
{id: 2, name: "Test2"}
{id: 3, name: "Test3"}
{id: 4, name: "Test4"}
{id: 5, name: "Test5"}
listClass2
{id: 1, name: "Test2"}
{id: 2, name: "Test5"}
I need to find out if listClass2
name
property is in listClass1
name
.我需要找出
listClass2
name
属性是否在listClass1
name
。 I mean, if they match.我的意思是,如果他们匹配。 Otherwise return an error or -1.
否则返回错误或 -1。
Is there a more efficient way than looping twice?有没有比循环两次更有效的方法? That's all I could think of at the moment, so any help is appreciated.
这就是我目前所能想到的,所以任何帮助表示赞赏。
You can store one (larger of the two would be better) of the list's names into a set<string>
and iterate over the other list and see if the set contains that element.您可以将列表名称中的一个(两者中的较大者更好)存储到
set<string>
然后遍历另一个列表并查看该集合是否包含该元素。
That should reduce your running time from O(m * n) to O(m * log(n)).这应该将您的运行时间从 O(m * n) 减少到 O(m * log(n))。
PS: I believe using a hash table can further reduce that log(n) factor. PS:我相信使用哈希表可以进一步减少 log(n) 因素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.