3
  1. Why are the Container Adapters like std::stack or std::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?

  2. Why are the algorithms of the STL implemented as free functions, which expect iterators, and not as methods of the corresponding containers?

Jonas
  • 6,915
  • 8
  • 35
  • 53
mcAngular2
  • 299
  • 1
  • 14

1 Answers1

5

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 or std::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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523