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

Автор Dgeka24, история, 4 года назад, перевод, По-русски

Почему здесь it==it1?

    set<ll> st;
    st.insert(1);
    auto it = st.begin(); auto it1=st.begin();
    it1--;
    if(it==it1){
        cout << "HERE\n";
    }

Но если увеличить размер set, то it!=it1

    set<ll> st;
    st.insert(1); st.insert(2); st.insert(3);
    auto it = st.begin(); auto it1=st.begin();
    it1--;
    if(it==it1){
        cout << "HERE\n";
    }

А этот код вообще ломает программу?

    set<ll> st;
    auto it = st.begin(); auto it1=st.begin();
    it1--;
    if(it==it1){
        cout << "HERE\n";
    }

Заранее спасибо

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

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

If you decrement the begin() iterator, you get undefined behavior. That means the C++ standard does not define the behavior of your program, so as far as the standard is concerned, anything can happen. In practice, you can get all sorts of weird stuff since the compiler can assume UB never happens, and possibly optimize based on that assumption.