Adaptor Containers : What’s under the hood.

C++14 outlines 3 container adaptors: stack, queue, priority_queue. They are outlined in section [container.adaptors/23.6]. If you take a look at their constructors, you’ll notice they’re implemented in terms of other containers. Hence the “adaptor” part of their name. Looking specifically at queue, the constructor has a default parameter set to a deque, but allowing the parameter to be set to another type. Here’s the declaration:

template <class T, class Container = deque <T> >
class queue;

Your first question may be:
“Why does stack use a deque as its default underlying container?”

Your second question may be:
“What other types of containers should you use?”

If we look a the usage of a queue, we expect to be able to insert elements at the back of the container, remove from the front of the container, and read from both ends of the queue. Explicitly, this means an interface supporting front(), back(), pop_front(), push_back(). Let’s look at the available sequence containers [sequences / 23.2]: array, deque, forward_list, list, vector.

Continue readingAdaptor Containers : What’s under the hood.”

vector < bool >: What isn’t can’t be.

vector<bool> doesn’t behave like other STL containers. If you try to obtain a reference to a bool inside the container, you’ll end up with an rvalue. Probably not what you had in mind. Oddly, it IS standard compliant (more on this later). Therefore you can’t say it’s not “standard compliant” container. What it doesn’t follow is the optional sequence container operations format from table 101 in section [sequence.reqmts / 23.2.3]. This table states the format for operator [] to return a reference or a const_reference. Assuming in this case vector<T>, a reference would be a T& and a const_reference a const T&. In the case of vector<bool>, operator[] returns a “reference” which is a class (more on this later). So there you have it. vector<bool> is standards compliant, but doesn’t meet the container requirements.

Continue readingvector < bool >: What isn’t can’t be.