简体   繁体   中英

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 . I mean, if they match. Otherwise return an error or -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.

That should reduce your running time from O(m * n) to O(m * log(n)).

PS: I believe using a hash table can further reduce that log(n) factor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM