Why are the Container Adapters like
std::stack
orstd::queue
implemented as adapters and not as independent containers? Is it because you want e.g. a stack with an underlying memory managment of different Sequence Containers?Why are the algorithms of the STL implemented as free functions, which expect iterators, and not as methods of the corresponding containers?

- 6,915
- 8
- 35
- 53

- 299
- 1
- 14
-
3You should ask **one** question at once – Passer By Jul 02 '17 at 10:35
-
Re: **2.** https://stackoverflow.com/questions/44864338/why-not-implement-contains-function-in-c-containers/44864906#44864906 – Galik Jul 02 '17 at 10:58
-
@PasserBy These two questions are closely related, so I think it's fine to keep them together. – Sergey Kalinichenko Jul 02 '17 at 10:58
1 Answers
This is done to give programmers better control over the implementation. An ability to mix-and-match is incredibly powerful, because it lets you achieve more things with less code.
Why are the Container Adapters like
std::stack
orstd::queue
implemented as adapters
Because you can mix-and-match containers and adapters: depending on your needs, you can create a queue
based on a vector
, or a stack
based on a list
, and then change the implementation details by swapping in a container of different type.
Why are the algorithms of the STL implemented as free functions
To avoid coding them in multiple places. For example, a linear search in a vector remains the same linear search in a list, and can also be applied to other containers that have iterators.
Note that some containers do have member-functions specific to their implementation. For example, std::set
has find
method for faster non-linear search.

- 714,442
- 84
- 1,110
- 1,523