28

What is the difference between the front() and begin() functions that appears in many STL containers?

1
  • 8
    front() is identical to *begin(). Commented Feb 15, 2012 at 23:27

5 Answers 5

37

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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()).
6

front() returns a reference to the first element, begin() returns an iterator to it.

Note that you shouldn't call front on an empty container, but it's OK to call begin as long as you don't dereference the iterator that begin returns.

Comments

2

The front member returns a reference to the first member of a list or vector. The begin function returns an iterator (which is more like a pointer) initialized to the first member of a list, map, or vector.

Comments

1

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

0

front()

  1. Returns a reference to the first element of the array
  2. Provides direct access to the first element.
  3. Can modify the first element alone

begin()

  1. Returns an iterator pointing to the first element of the array.
  2. It is used to iterate over the array or access elements using iterator operations.
  3. Can modify elements through iteration

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.