hacker696969's blog

By hacker696969, history, 5 years ago, In English

Hello CF Community,

I am new to competitive programming and recently have been learning STL ,I wanted to ask that if i want to erase the smallest value and also keep on iterating, if I am writing the following code, I am getting garbage values.

I know that there are other ways to do this but I wanted a modification of my code ,and also I wanted to know that is it not possible to traverse set while simultaneously erasing elements.

Code
  • Vote: I like it
  • -6
  • Vote: I do not like it

| Write comment?
»
5 years ago, # |
  Vote: I like it +16 Vote: I do not like it

Your code isn't working because of it++. You are trying to increment an iterator to the erased element.

But it's possible to change your code:

set <int> s;
s.insert(1); s.insert(2); s.insert(3);
for(auto it = s.begin(); it != s.end();) {
    cout << *it << endl;
    it = s.erase(it);
}
  • »
    »
    5 years ago, # ^ |
      Vote: I like it +10 Vote: I do not like it

    Note that this works because set::erase when called with an iterator conveniently returns the iterator to the next element.

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

This will work I guess.

Spoiler