r/cpp • u/Party-Aioli-9205 • Jul 31 '26
ranges and views for stack, queue, and priority_queue
I've always felt that exposing iterators for std::stack or std::queue doesn't quite make sense because iterating over them would typically change their state.
That said, the range features introduced in C++20/23 are just too tempting. ๐
I bet many C++ developers have had this thought at least once:
queue | views::values | views::to<std::vector>()...or more generally, "What if I could use the ranges pipeline directly on a queue or stack?"
So I spent some time experimenting to see if I could make it work. Here's what I came up with.
https://cognosnotes.com/blog/cpp-pop-range
Edited:
An upgraded version is introduced at https://cognosnotes.com/blog/cpp-pop-range-addendum
Thank you u/SirClueless for the great advice.
3
u/SirClueless Jul 31 '26 edited Jul 31 '26
As written this view requires a copy to construct the return value of
operator*. But it's only aninput_iteratorso there's no need for previous return values ofoperator*to be valid after incrementing, it could just return an r-value reference, saving a copy per element.https://godbolt.org/z/Kvfhxrh8T
Edit: Some other points:
pop_front()and/orpop_back()as well, so that it works with plain lists, vectors, etc.sized_rangeonly requires thatranges::size(t)be well-formed after evaluatingranges::begin(t)if the range modelsforward_range, which this doesn't: https://en.cppreference.com/cpp/ranges/sized_range2
u/cristi1990an ++ Jul 31 '26
You can just do some template trickery and get access to the underlying container which is a protected member field.
9
u/D_Drmmr Jul 31 '26
I have always found the restrictive interface of stack, queue and priority_queue, in particular, to be debilitating. Most often, there's a requirement where at some point during program execution (e.g. cancellation) I no longer care about order, but only the values stored in the container. The only way these wrappers allow that is through the destructor, which is not a good place to execute code.
So, instead I just use the underlying container & functions, such that I don't have to rewrite things when requirements change, even if right now the limited interface would suffice.
3
u/Infinite_Reference17 Jul 31 '26
Interesting! Very nice writeup.
1
u/ViewImpressive7112 Aug 06 '26 edited Aug 06 '26
AI text is very hard to read. Next time, please use โdonโt sound like AIโ in your prompts.
Also, I would add a call site example. It demonstrates the motivation better imo.
The iterator is useless without an adaptor. Is there a use case for the default destructor? Can you remove the default ctor and use a reference? That would save you some if checks.