What is the difference between vector.back() and vector.end()?

Viewed 28772

I am a new C++ learner, and I read a code block about C++ STL accessing the last element from a vector.

Why does the code at line 6, 7, and 8 need to subtract 1 to be equal to that at line 5?

1.    std::vector<int> v;
2.    v.push_back(999);
3.    //fill up the vector
4.    //...

5.    int j = v.back();
6.    int j = v.[size-1]
7.    int j = v.at(v.size()-1)
8.    int j = *(v.end()-1)
7 Answers

back() just returns a reference to the last element. while end() returns a pointer or an iterator to the last element. Also, end() can be used to check the stopping condition when iteration is performed from the beginning using begin().

Related