Deleting multiple elements from STL hash_multiset

V

Varun Kacholia

I apologize if there exists a standard way of deleting multiple
elements from a STL hash_multiset (or even multiset for that matter)
that I am unaware of.
The problem, I see, with multisets is that you cannot obtain info to
uniquely identify
an element (eg: indices in a vector, or key in set/hash_set). Hence
what I'd like
to do is iterate over a multiset and delete elements while doing so.
Now I did read somewhere that deleting an element while iterating might
invalidate the iterator. If this is indeed true, the only way out I see
is the following:

hash_multiset<int> my_set;
// add elements

vector<hash_multiset<int>::iterator> > to_delete;

for (hash_multiset<int>::iterator it = my_set.begin();
it != my_set.end(); ++it) {
if (condition)
to_delete.push_back(it);
}

for (int i = 0; i < to_delete.size(); ++i)
my_set.erase(to_delete);


I would appreciate any inputs as to the correctness of the above code.
I did test it and it works fine for small sets, but I'd like to know if
this is
not recommended or if there exists an alternative way of doing it.

(digging in the STL code shows that iterators point to hashtable
buckets
and ht nodes, and test equality before deleting the element -- though
there
are no guarantees if this implementation would remain the same
tomorrow)
 
P

Pete Becker

Varun said:
Now I did read somewhere that deleting an element while iterating might
invalidate the iterator.

Erasing an element of an associative container invalidates iterators,
references, and pointers to that element. It doesn't affect iterators,
references, and pointers to other elements. So store a copy of the
iterator, increment the copy, then erase the element.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top