Sorry if this has bee开发者_运维知识库n 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)
?
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.
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.
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.
精彩评论