[ACCEPTED]-What is std::vector::front() used for?-vector

Accepted answer
Score: 27

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

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

Score: 17

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

Score: 6

Doing this provides something called static 16 polymorphism.

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

More Related questions