Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::forward_list - how to insert element at the end [duplicate]

Tags:

c++

c++11

stl

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?

like image 629
Johnny Pauling Avatar asked Apr 02 '13 13:04

Johnny Pauling


1 Answers

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).

like image 81
Mike Seymour Avatar answered Sep 23 '22 14:09

Mike Seymour