Resizing a std::list
is linear time since it needs to find the n
th element first.
But is it possible to point to an element (using iterator) and resize in constant time by declaring that the pointed-to element is the new last element?
It would be something like: make_last(const_iterator pos)
.
Unfortunately, in C++11 general std::list
splicing is O(n), in order to get O(1) size checking.
Otherwise you could have moved the undesired items to another list.
But even that's just a half solution, since the items have to be destroyed at some point. However, if constant time splicing was guaranteed this would make a temporary resize O(1).
A practical solution is to use eg std::vector
instead of std::list
.
Due to necessity of destroying it doesn't give you O(1) resizing either, except when the resizing discards a constant number of items at the end, but it avoids all that complexity.
With the decision to make std::list::size
a constant time operation, I do not know of any remaining reason to use std::list
for anything.
In C++03 you use erase on the first element you don't want - constant time iff the optimiser realises the elements don't need destruction.
In C++11 you're stuffed... it's obliged to work out the new size as Alf explains.
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.