When submitting a solution in C++, please select either C++14 (GCC 6-32) or C++17 (GCC 7-32) as your compiler. ×

Dgeka24's blog

By Dgeka24, history, 4 years ago, In English

Why is here it==it1?

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

But if increase size of 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";
    }

And this code just crushes the program?

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

Thanks in advance

  • Vote: I like it
  • -8
  • Vote: I do not like it

»
4 years ago, # |
  Vote: I like it +3 Vote: I do not like it

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.