简体   繁体   English

C ++中向量的.size()实际上做了什么?

[英]What does .size() for a vector in C++ actually do?

换句话说,.size()计算向量对象的每个元素,只要它被调用并返回该值,或者向量对象是否具有(size_t?)成员,该成员保存当前在向量中的元素数量,以及值这个成员是由.size()返回的?

What exactly a call to std::vector::size does depends on the particular implementation of the standard library. 究竟std::vector::size的调用取决于标准库的特定实现。 However, the standard places several constraints on what it can and cannot do. 但是,该标准对它能做什么和不能做什么都有一些限制 In particular, it requires a call to size to execute in constant time, which means it cannot count the elements (that would be linear in the container size, not constant). 特别是,它需要调用size以在恒定时间内执行,这意味着它不能计算元素(在容器大小中是线性的,而不是常量)。

A vector's implementation needs one pointer to point to the beginning of the vector, and then other two pieces of information: how large the vector's data currently is (how many elements in the vector), and how large the vector's capacity currently is (how large is the allocated data buffer). 向量的实现需要一个指针指向向量的开头,然后是其他两个信息:向量数据当前有多大(向量中有多少元素),以及当前向量的容量有多大(多大)是分配的数据缓冲区)。 The latter two can be implemented either as pointers, or as offsets from the beginning pointer. 后两者既可以作为指针实现,也可以作为beginning指针的偏移实现。 Either representation can be used to obtain the size of data in constant time: either return the offset directly, or compute it as end - beginning . 可以使用任一表示来获取恒定时间内的数据大小:直接返回偏移量,或者将其计算为end - beginning

You can verify the complexity requirement in the standard itself, or in suitable reference documentation . 您可以在标准本身或适当的参考文档中验证复杂性要求。

std::vector::size的实现依赖于实现,即使它需要在O(1)具有复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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