0

If I compile and run the following code with gcc it works fine - and I don't see why this shouldn't. However if I compile and run this peace of code with VC++ it fails and a popup says: "Expression: Vector iterators incompatible"

int main() {

    vector<int> v = { 1,2,3,4 };
    for(auto it = v.begin(); it != v.end(); )
    {
        if(*it% 2 == 0)
        {
            v.erase(it);
        }else
        {
            ++it;
        }
    }

    return 0;
}
blint587
  • 191
  • 1
  • 10
  • Technically, the error (or rather, debug assertion) isn't raised by Visual Studio, or Visual C++. It is raised by it's debug runtime library. – IInspectable Jul 29 '16 at 15:18
  • [`it` will be invalidated](http://www.cplusplus.com/reference/vector/vector/erase/) (see 'Iterator validity' section) – ForceBru Jul 29 '16 at 15:19
  • Unrelated to the error, have you considered using `std::remove_if` rather than a loop like this? – Andy M Jul 29 '16 at 15:21

1 Answers1

6

VC++ is right: it is invalidated when you call erase. You should probably use it = v.erase(it). It works by coincidence under gcc.

zneak
  • 134,922
  • 42
  • 253
  • 328