In the C++ standard library, list
is doubly-linked list; forward_list
is singly-linked list but supports Last-In-First-Out only.
However, the First-In-First-Out singly-linked list has been widely used for its low space-overhead than other list-like containers (except forward_list
). So I wonder:
Why does C++ not provide a First-In-First-Out singly-linked list?
You can easily create one yourself by augmenting forward_list
with a before-the-end iterator to implement back()
and push_back()
:
template<class T>
struct fifo_list {
std::forward_list<T> base;
std::forward_list<T>::iterator before_end = base.before_begin();
fifo_list(fifo_list const& other) { for (auto t : other.base) push_back(t); }
fifo_list(fifo_list&&) = default;
auto front() { return base.front(); }
void pop_front() { base.pop_front(); }
auto back() { return *before_end; }
void push_back(T t) { before_end = base.insert_after(before_end, t); }
};
This can then be used with the std::queue
adapter.
The overhead associated with maintaining the before_end
iterator is presumably the reason why this facility (back
and push_back
) is not included in forward_list
already.