Std :: forward_list - how to insert an element at the end

forward_list is the only linked list (unlike the standard list container). the list has functions to insert both front and back, but forward_list does not have a function to insert an element in the back (something like push_back). Why is it not possible to insert an item at the end of the list?

+4
source share
2 answers

This is a deliberate design solution, according to which forward_list should not have overhead compared to a singly linked list. This is noted in the C ++ 11 standard (23.3.4.1):

Note. forward_list is forward_list have zero space or time overhead compared to a single-user C-style list. Functions that run counter to this goal have been omitted.

Maintaining the pointer at the end of the list will add both the overhead of the space (for the pointer itself) and time costs (updating the pointer when elements are inserted or deleted at the end of the list).

+10
source

I have no better way to say this except:
because this is the definition of this data structure ... you need another operation, for example, push_back use a different data structure.

== EDIT == I will try to refine a bit:
It is true that if you have an iterator for the last push_back element, this is O (1).
BUT saving the iterator to the last element may have overhead in other operations such as erase .

-1
source

All Articles