Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL - Why std::forward_list has no size() method?

Tags:

I have been using C++11's forward_list as a container for fast insertions, without much memory overhead, since it is a singly linked list.

After realizing that forward_list does not have a size() method, I'm a bit confused about the reasoning behind that. Couldn't it just maintain a private field keeping track of nodes inserted and removed, hence, implementing an O(1) size() operation?

like image 310
LunaticSoul Avatar asked Aug 05 '15 02:08

LunaticSoul


People also ask

How to get size of forward_ list?

To get the size of forward lists, one can use std::distance() function. Approach: Since std::distance() function takes two iterators as arguments and it returns an integer, the std::begin() and std::end() function can be passed which points to the address of the first item and the address just after the last item.

What is std :: Forward_list?

std::forward_list is a container that supports fast insertion and removal of elements from anywhere in the container. Fast random access is not supported. It is implemented as a singly-linked list. Compared to std::list this container provides more space efficient storage when bidirectional iteration is not needed.

What is C++ Forward_list?

Forward lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence. Forward lists are implemented as singly-linked lists; Singly linked lists can store each of the elements they contain in different and unrelated storage locations.

How do I find out if a forward list is empty?

C++ empty() function is used to check if the forward list container is empty or not.


1 Answers

N2543 is the proposal, and it has a detailed discussion about size().

The choice between Option 3 [not providing size()] and Option 2 [providing a O(1) size()] is more a matter of judgment. I have chosen Option 3 for the same reason that I chose insert-after instead of insert-before: Option 3 is more consistent with the goal of zero overhead compared to a hand-written C-style linked list. Maintaining a count doubles the size of a forward_list object (one word for the list head and one for the count), and it slows down every operation that changes the number of nodes. In most cases this isn't a change in asymptotic complexity (the one change in asymptotic complexity is in one of the forms of splice), but it is nonzero overhead. It's a cost that all users would have to pay for, whether they need this feature or not, and, for users who care about maintaining a count, it's just as easy to maintain it outside the list, by incrementing the count with every insert and decrementing it with every erase, as it is to maintain the count within the list.

like image 142
T.C. Avatar answered Oct 11 '22 21:10

T.C.