[英]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?使用std::vector
调用vector.back()
和vector[vector.size() - 1]
之间有什么区别吗?
vector.back()
is simpler to read and write. vector.back()
更易于读写。 Also, more containers offer c.back()
than c[c.size() - 1]
, which is important for generic code.此外,更多容器提供c.back()
而不是c[c.size() - 1]
,这对于通用代码很重要。
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.back()
是一个 function 调用,写起来更短:它更简单。 vector[vector.size() - 1]
is two function calls and a subtraction, and longer to write: It is more complex. vector[vector.size() - 1]
是两次 function 调用和一次减法,写起来更长:它更复杂。
Behaviourally, they are the same for std::vector
.在行为上,它们对于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).但是back
更通用,可以与所有标准双向容器一起使用( std::forward_list
是唯一不支持它的标准容器)。 operator[]
is only supported by random access containers. operator[]
仅受随机访问容器支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.