What is the difference between the front() and begin() functions that appears in many STL containers?
5 Answers
begin() returns an iterator that can be used to iterate through the collection, while front() just returns a reference to the first element of the collection.
1 Comment
David Rodríguez - dribeas
+1 Just to make things more explicit (or maybe complicate):
&c.front() == &*c.begin() for any container that has at least one element. Comparing the address-of the expressions is used to demonstrate that it is not the values that are the same, but the objects (i.e. c.front() yields a reference to the same object that dereferencing the begin iterator *c.begin()).From http://www.cplusplus.com/reference/stl/vector/begin/ (literally the first google result for "vector::begin"):
Notice that unlike member
vector::front, which returns a reference to the first element, this function returns a random access iterator.
Comments
front()
- Returns a reference to the first element of the array
- Provides direct access to the first element.
- Can modify the first element alone
begin()
- Returns an iterator pointing to the first element of the array.
- It is used to iterate over the array or access elements using iterator operations.
- Can modify elements through iteration
front()is identical to*begin().