c++ - How to compute in-place set difference of two multisets? -


suppose have 2 multisets. want remove elements occur in second multiset first multiset, respecting number of times each element occurs in each multiset. example, if multiset a contains 1 5 times, , multiset b 2 times, when compute a -= b, 2 instances of 1 should removed a.

here code accomplishes this:

 multiset<int> a;  multiset<int> b;   // remove items occur in b a, respecting count ("a -= b")  (multiset<int>::iterator = b.begin(); != b.end(); i++) {     if (a.count(*i) < 1) {        // error      }     // a.erase(*i) remove elements equal *i a,      // want remove one.  a.find(*i) gives iterator first     // occurrence of *i in a.     a.erase(a.find(*i));   } 

surely there's better / more idiomatic way?

while std::set_difference requires put elements new set, can still optimize moving elements original set new 1 , swapping both afterwards (ok, ints moving isn't neccessary, way algorithm keeps flexible , generic).

std::multiset<int> c; std::set_difference(std::make_move_iterator(a.begin()),                      std::make_move_iterator(a.end()),                      b.begin(), b.end(),                      std::inserter(c, c.begin())); a.swap(c); 

not in-place, nearly , still quite idiomatic while being linear in complexity (since std::insert_iterator provide proper hint std::multiset::insert).


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -