Sequence Containers - why a few expressions are only supported by a few sequence containers

Viewed 49

I was going thru Sequence Containers named requirement : https://en.cppreference.com/w/cpp/named_req/SequenceContainer

But then it states that the following expressions must be valid and have their specified effects for the sequence containers named:

example:

seqcnt.pop_front()               Destroys the first element.                        deque / list / forward_list
seqcnt.pop_back()                Destroys the last element                          deque / list / vector

Why are all expressions not supported by all sequence containers?

1 Answers

Because sequence containers are different and have different performance-friendly capabilities.

A std::array is a fixed-length container; you cannot remove elements from it, because it's length is fixed at compile-time. So functions that remove (or insert) elements aren't present.

std::forward_list, by definition, goes in one direction: front to back. Removing the first element is cheap; it only requires taking the first node, deleting it, and making the second node the new first node. To remove the last element would require iterating through the entire list to reach the element before the end iterator. That's not performance-friendly; if you want to do it yourself, you can. But because of its O(n) performance, the standard isn't going to suggest that this is a good idea by making a function specifically to do just that.

std::vector is a dynamically-sized array. Removal at the end is a constant-time operation, since you're just destroying the last element and decrementing a pointer. But removal at the beginning requires shifting all of the elements left in the array down one. This is not performance-friendly, so the standard isn't going to suggest that this is a good idea by making a function specifically to do just that.

Related