简体   繁体   中英

What is std::vector::front() used for?

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 eg 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.

如果myvector的类型更改为另一种不可索引的数据类型(例如列表),则不必更改访问容器前端的代码。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM