简体   繁体   中英

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. 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. In that case, is there any reason that resize downward would ever not be O(1) time?

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) .

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.

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