C / C ++ is an effective way to compare two lists and find missing items

I have two lists, L 1 and L 2data containing multiple elements, each unique, abstract data type (i.e. structs). Each of the two lists:

  • May contain from zero to one hundred (inclusive) elements.
  • It does not contain duplicate elements (each element is unique).
  • May or may not contain items in another list (i.e.: L 1 and L 2 may be identical or contain completely different elements).
  • Not sorted.
  • The container is stored at the lowest level std::vector<myStruct>.

I usually expect a new item to be added periodically to L 2, or the item is subtracted / removed from it. I am trying to identify the differences in the two lists as efficiently as possible (i.e. with minimal comparisons):

  • If there is no entry in L 2 and is present in L 1, Perform one operation: Handle_Missing_Element().
  • If the entry is in L 2 and not present in L 1, Perform other operations: Handle_New_Element().

After performing the above checks L 1 set to L 2, and after some time in the future L 2 checked again.

How can I make out the differences between the two lists? There are two approaches that I can think of:

  • Compare both lists through each possible combination of elements. Perhaps O (n 2 ) is the execution complexity (terrible).

bool found;
for i in 1 .. L2->length()
  found = false;
  for j in 1 .. L1->length()
    if (L1[j] == L2[i]
      // Found duplicate entry
      found = true;
    fi
  endfor
endfor
  1. -, . , . , , . / . , vector::push_back() , .

++? , , , , , , "" "" .

.

+4
4

/ . , vector::push_back() , .

, , . <algorithm> , . std::vector::push_back std::vector::insert std::lower_bound, , .

auto insert_pos = std::lower_bound( L2.begin(), L2.end(), value );
if( insert_pos == L2.end() || *insert_pos != value )
{
    L2.insert( insert_pos, value );
}

O (logN), N , .

zipping :

auto it1 = L1.begin();
auto it2 = L2.begin();

while( it1 != L1.end() && it2 != L2.end() )
{
    if( *it1 < *it2 ) {
        Handle_Missing( *it1++ );
    } else if( *it2 < *it1 ) {
        Handle_New( *it2++ );
    } else {
        it1++;
        it2++;
    }
}

while( it1 != L1.end() ) Handle_Missing( *it1++ );
while( it2 != L2.end() ) Handle_New( *it2++ );
+2

- ? , - . , " ". ++ STL, map .

  • L1 map, .
  • L2, L2 , L1.
  • L2, - , L1 ( map.find(), STL). , Handle_New_Element().
  • L2, - L1, Handle_Missing_Element().
+3

, , std::set. O (log n), O (n). , std::multiset.

+3

, . , .

x L2, L1. y x y.

x L2, L1. y L1 y. x , .

, . - , .

O (| L1 |) , O (| L1 | + | L2 |) . , .

EDIT: , 0, 1 - .

EDIT2: , -. - L1, O (1). BTW, L1 , -, .

+2
source

All Articles