Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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

like image 840
Jan Berndt Avatar asked Jan 18 '26 23:01

Jan Berndt


1 Answers

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.

like image 61
Deduplicator Avatar answered Jan 20 '26 13:01

Deduplicator