views:

251

answers:

3

Sorry if this has been asked before, but I am wondering what the use of std::vector::front() is.

Is there a reason to use e.g. myvector.front() rather than myvector[0] or myvector.at(0)?

+14  A: 

Some of the generic algorithms that also work on lists use it.

This is an example of a general principle: if you provide accessors for all the semantics you support, not just the implementation you support, it is easier to write generically and therefore easier to reuse code.

dmckee
+1: Solid edit.
John Dibling
Ah, so it is more about consistency with other container classes.Just out of curiosity: is vector::front() equivalent to [0] or to at(0)?I mean, what happens if the vector is empty?
Tim
@Tim: Good question. Wikipedia says undefined behavior: http://en.wikipedia.org/wiki/Vector_(C%2B%2B) and http://fredosaurus.com/notes-cpp/stl-containers/sequence-functions.html says the same as [0] which I suppose is also undefined if the vector is empty.
dmckee
Looks like my question is completely answered now. Thanks for your help everyone!
Tim
+9  A: 

If the type of myvector changes to another data type that is not indexable, such as a list, you will not have to change code that accesses the front of the container.

xzqx
Your and the previous poster's answers should be combined. Abstract concept + concrete example for the win.
Omnifarious
+2  A: 

Doing this provides something called static polymorphism.

Let's say I've written an algorithm using a queue class. It has a front() function to get the next element of the queue, and an enqueue() function to add to the end of the queue. Now let's say I discovered that this queue class is written poorly and very slow, and I'd rather use std::vector which is much faster (I know there's a std::queue, this is just an example). If the only way to get the first element of a std::vector was with v[0], I'd have to go through my code and replace all my calls to front() with [0]. But by implementing front(), std::vector can now be a drop-in replacement for my queue class. The only code I have to change is the type of the container in my algorithm.

Colin