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.
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.
Syntax:
size = distance(forward_list.begin(), forward_list.end());
Below is the C++ code to implement the above approach:
C++14
// C++ program to implement // the above approach #include <forward_list> #include <iostream> using namespace std; // Driver code int main() { forward_list< int > l1 = { 3, 5, 6, 9, 6 }; // l.size() will throw an error, since // there is no size() method for // forward_list. So, to calculate the // size, we will use std::distance(iterator1, // iterator2), where iterator1 will be // l.begin() and iterator2 will be l.end() int size = distance(l1.begin(), l1.end()); cout << "Size of l1 is : " << size << endl; l1. remove (6); // It will erase all instances of 6 // from the list size = distance(l1.begin(), l1.end()); cout << "Size of l1, after removing all" << " instances of 6 is : " << size << endl; forward_list< int > l2 = { 6, 11, 0 }; int size2 = distance(l2.begin(), l2.end()); cout << "Size of l2, before assigning" << " it to l1 : " << size2 << endl; l1.splice_after(l1.begin(), l2); // It will assign l2 to l at the // provided iterator, making l1 // as empty. size = distance(l1.begin(), l1.end()); size2 = distance(l2.begin(), l2.end()); cout << "Size of l1, after assigning" << " l2 to it : " << size << endl; cout << "Size of l2, after assigning" << " it to l1 : " << size2 << endl; } |
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...