简体   繁体   English

如果元素类型是原语,std :: vector :: resize()向下取O(1)时间吗?

[英]does std::vector::resize() downward take O(1) time if the element type is a primitive?

I understand that in C++, std::vector::resize allocates no new memory when the new size is smaller. 据我所知,在C ++中,当新的大小较小时, std::vector::resize不会分配新的内存。 Also, if the element type is a user-defined class with a destructor, that destructor may be called for every element that is "lost" in the resize, so in that case the running time would be linear in the size difference. 此外,如果元素类型是具有析构函数的用户定义类,则可以为调整大小中“丢失”的每个元素调用该析构函数,因此在这种情况下,运行时间在大小差异中将是线性的。

However, if the element type were a primitive, eg std::vector<int> , there's no destructor to call. 但是,如果元素类型是基元,例如std::vector<int> ,则没有析构函数可以调用。 In that case, is there any reason that resize downward would ever not be O(1) time? 在这种情况下,是否有任何理由向下resize不会是O(1)时间?

There seems to be no guarantee in the standard for this complexity. 对于这种复杂性,似乎无法保证标准。 However, as you point out, there seems to be no reason for greater-than-constant complexity either in that case. 但是,正如您所指出的那样,在这种情况下似乎没有理由要求复杂性大于常数。 Complexity is only guaranteed to be O(n) . 复杂性仅保证为O(n)

I'd be surprised to find a compiler that implemented it as linear for primitive types, but the best way to be sure with your compiler setup would be to make a simple test. 我很惊讶地发现编译器将它实现为基本类型的线性,但是确保编译器设置的最佳方法是进行简单的测试。

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

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