Two questions regarding C ++ containers
-
Why are container adapters like
std::stack
or arestd::queue
implemented as adapters and not as independent containers? Is it because you want, for example, a stack with basic memory management of different sequence containers? -
Why are STL algorithms implemented as free functions waiting for iterators and not as methods of the respective containers?
source to share
This is done in order to give programmers better control over the implementation. The mix-and-match ability is incredibly powerful because it allows you to accomplish more things with less code.
Why are container adapters like
std::stack
orstd::queue
are implemented as adapters
Because you can mix and match containers and adapters: depending on your needs, you can create queue
based on vector
or stack
based on list
and then change the implementation details by replacing in a different container type.
Why STL algorithms are 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 with iterators.
Note that some containers have member functions specific to their implementation. For example, it std::set
has a method find
for faster nonlinear search .
source to share