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

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
主站蜘蛛池模板: 二连浩特市| 新安县| 永嘉县| 平舆县| 安泽县| 富蕴县| 独山县| 万州区| 集安市| 息烽县| 营口市| 榆中县| 遂昌县| 玉门市| 五莲县| 河西区| 广元市| 英超| 开化县| 岑溪市| 乐亭县| 漳平市| 西贡区| 休宁县| 连平县| 乌苏市| 右玉县| 镇巴县| 施秉县| 三江| 策勒县| 和田市| 阿拉尔市| 天峻县| 大名县| 麦盖提县| 贵定县| 绩溪县| 迁安市| 宁明县| 平江县|