c++ - Reconcile two lists -
so have 2 different lists, different formats , structure need reconciled. essentially, set b needs match what's in set a, want preserve state of existing items in set b , not overwrite them what's in set a.
for reference, list doesn't mean list. "lists" come in couple of different forms straight arrays maps. use standard iterators access elements.
the way typically handle so...
for item in lista if listb contains item mark item in list b visited else add item list b item in listb if visited true continue else add item removelist item in removelist remove item list b
this works , real way can think of it. don't how many iterations have though, having 3 loops back feels wrong. however, since i'm using iterators can't remove lists while i'm checking them , instead have add them third remove list.
in potential answers please keep in mind speed , memory footprint more important me how easy write code.
my question boils down -- there better way i'm not thinking of?
i'm in c++/c fwiw, though think solution language agnostic.
thanks!
here's way may more efficient:
removelist = listb item in lista if listb contains item remove item removelist else add item listb item in removelist remove item listb
so instead of building removelist nothing, starts off , has items removed it.
you make more efficient having removelist store indexes rather actual items. long items added end of listb in initial loop, , items removed in reverse order, indexes should still valid.
in fact it's simpler if replace removelist boolean array of items keep. algorithm becomes this:
initialise itemstokeep false savedlistlength = length of listb item in lista offset = find item in listb if found mark itemstokeep[offset] true else add item listb offset savedlistlength-1 down 0 if itemstokeep[offset] false remove offset listb
this avoids need copy removelist initially. , expense of itemstokeep array surely no worse whatever using keep track of visted items in algorithm.
to extent suitable algorithm maybe depend on form of lists (i.e. vectors, or linked lists, etc.) think approach has potential more effecient either way.
Comments
Post a Comment