Deleting multiple elements from STL hash_multiset

Discussion in 'C++' started by Varun Kacholia, Mar 31, 2006.

  1. 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)
    Varun Kacholia, Mar 31, 2006
    #1
    1. Advertising

  2. Varun  Kacholia

    Pete Becker Guest

    Varun Kacholia wrote:

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

    --

    Pete Becker
    Roundhouse Consulting, Ltd.
    Pete Becker, Apr 1, 2006
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Kenneth Massey
    Replies:
    3
    Views:
    1,622
    Kenneth Massey
    Jul 21, 2004
  2. Replies:
    5
    Views:
    2,950
    Earl Purple
    Dec 18, 2005
  3. Replies:
    4
    Views:
    776
    Daniel T.
    Feb 16, 2006
  4. Harry Barker
    Replies:
    2
    Views:
    500
    Alf P. Steinbach
    Apr 19, 2006
  5. crea
    Replies:
    2
    Views:
    388
    Nobody
    Dec 28, 2012
Loading...

Share This Page