官术网_书友最值得收藏!

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
主站蜘蛛池模板: 山阴县| 灵石县| 茌平县| 遂平县| 舟山市| 江达县| 安义县| 鞍山市| 梁山县| 新河县| 腾冲县| 大名县| 翼城县| 兴安县| 云龙县| 罗城| 稷山县| 滦平县| 军事| 伊金霍洛旗| 澄城县| 仁布县| 东山县| 伊川县| 慈溪市| 澜沧| 察哈| 遂溪县| 桐庐县| 景东| 天门市| 巴东县| 廊坊市| 桦南县| 迁西县| 马关县| 于都县| 农安县| 尉犁县| 龙口市| 莒南县|