使用gcc编译的C++在VC++ 14中有效且无效

bli*_*587 0 c++ visual-c++

如果我使用gcc编译并运行以下代码,它可以正常工作 - 我不明白为什么这不应该.但是,如果我使用VC++编译并运行这段代码,它会失败并且弹出窗口显示:"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;
}
Run Code Online (Sandbox Code Playgroud)

zne*_*eak 6

VC++是对的:it调用时无效erase.你可能应该使用it = v.erase(it).它在gcc下巧合.