简体   繁体   中英

Complexity of downsizing STL vector

What is the time complexity of downsizing (reducing the size) an std::vector<int> ? I get that it does not reallocate memory. On custom classes, it may need to call destructors for all elements that are removed. But with integers, will the downsizing happen in constant time?

Depends on what you mean by "reducing the size" of a vector.

Usually, people remove elements from a vector by calling erase . If you erase stuff at the end of the vector, then things are simple, and all that happens is that the elements are destructed - which, as Remy pointed out, is a no-op for int s.

If you're erasing from somewhere other than the end, then elements have to be shuffled around, and that takes time. Fortunately for your use case, copying an int is cheap, but it's not zero. So there's no way that removing an element from the beginning/middle of a vector can be constant time.

Note: calling resize on a vector to make it smaller removes elements at the end.

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