Adaptors

Adaptors are template classes that provide an existing class with a new interface. Adaptors can be used to create new interfaces for containers or iterators.

The STL provides container adaptors, some which change the behavior of an underlying container, some which allow a non-STL data structure to be used in STL algorithms.

Container Adaptors

Often it is desirable to create a specialized container from an existing, more general container. The operations of the new container are implemented using the underlying operations of the existing containers. Container adaptors are used to create a new container by mapping the interface of an existing container to that of the new container. This allows new containers to be created without much additional effort, since most of the functionality is already provided by the existing container.

The STL provides three container adaptors:

·         stack<Container>;

·          queue<Container>;

·         deque<Container>.

The following program demonstrates the use of a stack that has been implemented as a vector:

#include <vector.h>
#include <stack.h>
void main()  {
   stack <vector<int> > st;
   for (int i=0; i < 10; i++)
      st.push (i);
   while ( !st.empty() ) {
      cout << st.top() << " ";
      st.pop();
   }
   cout << endl;
}

iterator adaptors

Adaptors can also be used to extend the functionality of an existing iterator. The STL provides three iterator adaptors:

The STL provides three different insert iterators that instead of overwriting the value at that location, actually insert a value there. Each type of adaptor performs the insertion into the container in a different place.