Iterator assignment in state - vector iterators are incompatible

I have a wrapper for std::vector, and I implemented a function that replaces a section in a vector with another vector. I tried to put the iterator assignment directly in the condition ifand got unexpected results .

I am using Visual Studio 2013 and with a FAILcertain, I received a debugging debugging error! - vector iterators are incompatible . Is it possible that the condition is evaluated from right to left? I can not handle it.

This is (poorly implemented) code that reproduces my problem - designed to replace the 3rd and 4th elements vecwith the 1st and 2nd elements vec_second:

#include <iostream>
#include <vector>
#include <iterator>
using std::cout;

//#define FAIL

int main()
{
    std::vector<int> vec = {1, 2, 3, 4, 5};
    std::vector<int> vec_second = {6, 7};

    auto it = vec.begin() + 2;

#ifndef FAIL
    it = vec.erase(it, it + vec_second.size());

    if(it == vec.end())
#else
    if((it = vec.erase(it, it + vec_second.size())) == vec.end())
#endif
        vec.reserve(vec.size() + vec_second.size());

    vec.insert(it, vec_second.begin(), vec_second.end());

    for(auto const& x : vec)
        cout << x << " ";
}

But it works great on the Coliru GCC .

+4
1
if((it = vec.erase(it, it + vec_second.size())) == vec.end())

, erase end . end, erase, undefined.

#ifndef FAIL - .

+7

All Articles