Блог пользователя arnav2004

Автор arnav2004, история, 5 лет назад, По-английски

I solving this problem Link to problem. I could not solve it hence checked other people's code. I saw this AC Code. AC Solution. I changed it just a little bit and it got runtime error. Runtime Error Code. As you can see the only difference is in the for loop in the 'dfs' function. Can anyone tell me the reason for the code to receive a runtime error.

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
5 лет назад, скрыть # |
← Rev. 3  
Проголосовать: нравится 0 Проголосовать: не нравится

.

»
5 лет назад, скрыть # |
← Rev. 2  
Проголосовать: нравится +1 Проголосовать: не нравится

You should never delete element in a range-based for loop. In the AC code, the element are deleted later after the for loop. If you still wanna delete element while iterating:

for(auto it = s.begin(); it != s.end(); ){
    if(/*delete condition here*/) it = s.erase(it); //return the next iterator
    else ++it;
}

I still prefer to delete outside the loop than delete inside the loop. From my experience, set is a magic data structure in C++, sometime you couldn't find where your code cause RTE without printing every possible variables, debugger can't help. So be careful, otherwise you will have a great time debugging hopelessly.