Odd values printed when dereferencing the end iterator of a vector

后端 未结 4 1482
[愿得一人]
[愿得一人] 2021-01-06 13:33

I have a vector storing {1,2,3,4,5}. I tried to print *(vec.end()) and got back the result 6. I don\'t know how to explain this. Similarly, calling vec.fi

4条回答
  •  执笔经年
    2021-01-06 14:08

    In C++ containers, the end iterator gives an iterator one past the end of the elements of the container. It's not safe to dereference the iterator because it's not actually looking at an element. You get undefined behavior if you try to do this - it might print something sensible, but it might just immediately crash the program.

    Hope this helps!

提交回复
热议问题