简体   繁体   中英

Difference between vector.back() and vector[vector.size() - 1]?

Is there any difference between calling vector.back() and vector[vector.size() - 1] with std::vector 's?

vector.back() is simpler to read and write. Also, more containers offer c.back() than c[c.size() - 1] , which is important for generic code.

In a debug-runtime, both are equally likely to be trapped on empty containers, nor is the resulting code and thus their performance when using optimization expected to differ significantly.

vector.back() is one function call and shorter to write: It is simpler. vector[vector.size() - 1] is two function calls and a subtraction, and longer to write: It is more complex.

Behaviourally, they are the same for std::vector . However back is more generic, and can be used with all standard bidirectional containers ( std::forward_list being the only standard container that doesn't support it). operator[] is only supported by random access containers.

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