Пожалуйста, прочтите новое правило об ограничении использования AI-инструментов. ×

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

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

Look at these submissions:

26586468

26586481

They have one different that is using:

for(int c:vec)

instead of:

for(int j=0;j<vec.size();j++){
    int c = vec[j];
    ...
}

one get Runtime and other one is Accepted.

I think that is happen because I change the size of my vector in the "for" However the size of it will be constant after each step.

Can I anyone explain? Tnks a lot.

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

»
7 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

I guess the first for stands for this:

for (auto it = v.begin(); it != v.end(); ++it)

Though, if it == v.end() — 1, you delete last element in vector and then make ++it, iterator will never become equal to v.end().

»
7 лет назад, # |
  Проголосовать: нравится +28 Проголосовать: не нравится

Changing the size may cause reallocation of memory for capacity increasing. As the result, iterators, that are used in range-based for loop, become invalid.

  • »
    »
    7 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

    I'm not sure how vector iterators are realised in gcc, but theoretically they can handle it.

    • »
      »
      »
      7 лет назад, # ^ |
        Проголосовать: нравится 0 Проголосовать: не нравится

      They are just a pointers, so they cant. Not only in gcc, but in VC++ and Clang too.