Odd values printed when dereferencing the end iterator of a vector

后端 未结 4 1513
[愿得一人]
[愿得一人] 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条回答
  •  萌比男神i
    2021-01-06 14:01

    Never try to use end() of any stl container because it does not point to a valid data. It always point to a chunk of memory that is located after the actual data. Use end() only to check whether your iterator has come to end or not. This image clearly explains where end() is located in default (non-reversed) range:

    STL Container's begin and end

提交回复
热议问题