Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

A templatised approach to queues and stacks

26 views
Skip to first unread message

Paul

unread,
Dec 26, 2015, 7:42:28 AM12/26/15
to
A depth-first search and a breadth-first search are almost identical except that breadth-first uses a queue and depth-first uses a stack.

Suppose we want code that does both. What's the most natural way to take advantage of the similarity to avoid code duplication, using the STL containers? I don't think templates will work because stack is a container adaptor rather than a type. There's also the problem that the name for the topmost element changes -- top() for a stack but front() for a queue.

Thank you,

Paul

Alf P. Steinbach

unread,
Dec 26, 2015, 8:14:29 AM12/26/15
to
Well, there's std::dequeue for you.

Cheers & hth.,

- Alf

Öö Tiib

unread,
Dec 26, 2015, 8:26:10 AM12/26/15
to
On Saturday, 26 December 2015 14:42:28 UTC+2, Paul wrote:
> A depth-first search and a breadth-first search are almost identical
> except that breadth-first uses a queue and depth-first uses a stack.

You conflate idea and implementation here. Neither algorithm deals with
underlying container types and some third container adaptor for example
'std::priority_queue' can be used for storing progress of both algorithms.

>
> Suppose we want code that does both. What's the most natural way to
> take advantage of the similarity to avoid code duplication, using the
> STL containers? I don't think templates will work because stack is
> a container adaptor rather than a type.

What it has to do with anything? AFAIK 'std::queue' is as much a
container adaptor as is 'std::stack'.

> There's also the problem that the name for the topmost element
> changes -- top() for a stack but front() for a queue.

You can always use lambdas. Lambdas have name only if you name those
and that compilers tend to inline if possible. However what is the
supposed gain here?
0 new messages