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)
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)