2 つのマルチセットがあるとします。各要素が各 multiset に出現する回数を考慮して、最初の multiset から 2 番目の multiset に出現するすべての要素を削除したいと考えています。たとえば、multisetaに15 回含まれ、multisetにb2 回含まれている場合、 を計算するa -= bと、 から のインスタンスを 2 つだけ1削除する必要がありますa。
これを実現するコードを次に示します。
multiset<int> a;
multiset<int> b;
// remove all items that occur in b from a, respecting count ("a -= b")
for (multiset<int>::iterator i = b.begin(); i != b.end(); i++) {
if (a.count(*i) < 1) {
// error
}
// a.erase(*i) would remove ALL elements equal to *i from a, but we
// only want to remove one. a.find(*i) gives an iterator to the first
// occurrence of *i in a.
a.erase(a.find(*i));
}
確かに、より良い/より慣用的な方法がありますか?