Reputation: 5197
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.
Upvotes: 0
Views: 414
Reputation: 5523
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)).
P.S.: I believe using a hash table can further reduce that log(n) factor.
Upvotes: 1