I am very confused about the const version and non-const version member function like below:
value_type& top() { return this.item }
const value_type& top() const { return this.item }
What is the difference between these two functions? In what situation would they be used?
In short, they’re used to add ‘const correctness’ to your program.
This is used to provide mutable access to
item. It is used so you can modify the element in the container.For example:
One common example for this pattern is returning mutable access to an element with
vector::operator[int index].On the other hand:
This is used to provide
constaccess toitem. It’s more restrictive than the previous version – but it has one advantage – you can call it on a const object.To follow the vector example: