code_warrior's blog

By code_warrior, history, 4 years ago, In English

Hello,friends! Recently , i was solving a problem on data structures from codeforces Merge Equals. In this problem , i used a sorted list of pairs stored in a set. I wanted to get the second element just greater than or equal to a given element(a pair in this case) . For ,this i used lower_bound function to first get the required element and the incremented the iterator. But, unfortunately ,it gave me the wrong answer. But, when i just removed the element corresponding to iterator (before incrementing it) and the again used it=st.lower_bound({x,y}), it gave me the right answer. So, I want to ask why accessing a pair by incrementing iterator doesn't work in my case. If anyone can throw some light on the concerned issue, it would be highly beneficial for me and others too. Accepted Code Wrong Answer Code

  • Vote: I like it
  • -3
  • Vote: I do not like it

| Write comment?
»
4 years ago, # |
  Vote: I like it 0 Vote: I do not like it

You must not erase an element, and then dereference an iterator pointing to it.

      st.erase(*it);
      it++;
      p=*it;

To be save follow the rule: Every change of the set invalidates all iterators created prior to the change.

For use of erase() see http://www.cplusplus.com/reference/set/set/erase/ and note the return value of it.