SalooP's blog

By SalooP, history, 8 years ago, In English

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.

  • Vote: I like it
  • +15
  • Vote: I do not like it

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

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

»
8 years ago, # |
  Vote: I like it +28 Vote: I do not like it

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.

  • »
    »
    8 years ago, # ^ |
    Rev. 2   Vote: I like it 0 Vote: I do not like it

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

    • »
      »
      »
      8 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

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