Mastering C++ Programming
上QQ阅读APP看书,第一时间看更新

Forward list

The STL's forward_list container is built on top of a singly linked list data structure; hence, it only supports navigation in the forward direction. As forward_list consumes one less pointer for every node in terms of memory and runtime, it is considered more efficient compared with the list container. However, as price for the extra edge of performance advantage, forward_list had to give up some functionalities.  

The following diagram shows the internal data-structure used in forward_list:

Let's explore the following sample code:

#include <iostream>
#include <forward_list>
#include <iterator>
#include <algorithm>
using namespace std;

int main ( ) {

forward_list<int> l = { 10, 10, 20, 30, 45, 45, 50 };

cout << "\nlist with all values ..." << endl;
copy ( l.begin(), l.end(), ostream_iterator<int>(cout, "\t") );

cout << "\nSize of list with duplicates is " << distance( l.begin(), l.end() ) << endl;

l.unique();

cout << "\nSize of list without duplicates is " << distance( l.begin(), l.end() ) << endl;

l.resize( distance( l.begin(), l.end() ) );

cout << "\nlist after removing duplicates ..." << endl;
copy ( l.begin(), l.end(), ostream_iterator<int>(cout, "\t") );
cout << endl;

return 0;

}

The output can be viewed with the following command:

./a.out

The output will be as follows:

list with all values ...
10 10 20 30 45 45 50
Size of list with duplicates is 7

Size of list without duplicates is 5

list after removing duplicates ...
10 20 30 45 50