std::forward_list - how to insert element at the end

c++, c++11, stl

Solution

It's a deliberate design decision that `forward_list` should carry no overhead when compared to a singly-linked list. This is noted in the C++11 standard (23.3.4.1):

Note: It is intended that `forward_list` have zero space or time overhead relative to a hand-written C-style singly linked list. Features that would conflict with that goal have been omitted.

Maintaining a pointer to the end of the list would add both space overhead (for the pointer itself) and time overhead (updating the pointer when elements are inserted or erased at the end of the list).

Problem

forward_list is a single linked list (unlike the standard list container). list has functions to insert both in front and back but forward_list hasn't a function to insert an element in the back (something like push_back). Why isn't it possible to insert an element at the back of the list?

Original source

Related problems