When to use C++ forward_list

前端 未结 2 1974
轻奢々
轻奢々 2021-02-05 09:23

I am kind of new to C++, and reading the book \"The C++ Programming Language (4th edition)\". When reading chapter of \"STL Containers\", the book has a introduction to forward_

2条回答
  •  时光取名叫无心
    2021-02-05 09:43

    Here is the node structure used in the std::list and std::forward_list:

    struct _List_node      // list node
    {   
      _Voidptr _Next;      // successor node, or first element if head
      _Voidptr _Prev;      // predecessor node, or last element if head
      _Value_type _Myval;  // the stored value, unused if head
    };
    
    struct _Flist_node     // forward_list node
    {   
      _Voidptr _Next;      // successor node
      _Value_type _Myval;  // the stored value
    };
    

    Space calculation:

    sizeof(_List_node)  = 2 * sizeof(_Voidptr) + sizeof(_Value_type)
    sizeof(_Flist_node) = 1 * sizeof(_Voidptr) + sizeof(_Value_type)
    

    if sizeof(_Value_type) is same or approximately equal to sizeof(_Voidptr) then we have:

    sizeof(_List_node)  ~ 3 * sizeof(_Voidptr)
    sizeof(_Flist_node) ~ 2 * sizeof(_Voidptr)
    

    If sizeof(_Value_type) >> sizeof(_Voidptr) then the savings is negligible. But for storing smaller objects using forward_list has ~1.5x savings in space (provided you don't need a reverse iterator.)

提交回复
热议问题