How to find Size of std::forward_list in C++ STL
Forward list in standard template library of C++. It comes under #include<forward_list> header file. It is implemented as a singly linked list. It was introduced in C++ 11 for the first time. Forward lists are sequence containers that allow constant time insert and erase operations from anywhere within the sequence. In the case of a forward list, fast random access is not supported.
Unlike other STL libraries, std::forward_list does not have any size() method. Hence, in this article, we will show you how to get the size of a std::forward_list in C++ STL.
There is a problem in retrieving the size of forward lists because std::forward_list doesn’t have any std::size() member function. To get the size of forward lists, one can use std::distance() function.
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.
size = distance(forward_list.begin(), forward_list.end());
Below is the C++ code to implement the above approach:
Size of l1 is : 5 Size of l1, after removing all instances of 6 is : 3 Size of l2, before assigning it to l1 : 3 Size of l1, after assigning l2 to it : 6 Size of l2, after assigning it to l1 : 0
Please Login to comment...