1 forward_list::front() and forward_list::empty() in C++ STL
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements. forward list 是单链表,在插入、删除和移动比其他容易好用,插入和删除是常量级别的,和其他链表不同的是,仅跟踪下一个元素的位置,list是跟踪前面和后面的元素。
forward_list::front()
This function is used to reference the first element of the forward list container. This function can be used to fetch the first element of a forward list. 获得forward list的第一个元素。
Syntax :
forwardlistname.front()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the first element of the container.
Examples:
Input : forward_list forwardlist{1, 2, 3, 4, 5};
forwardlist.front();
Output : 1
Input : forward_list forwardlist{0, 1, 2, 3, 4, 5};
forwardlist.front();
Output : 0
Errors and Exceptions
1. If the forward list container is empty, it causes undefined behaviour.
2. It has a no exception throw guarantee if the forward list is not empty.
// CPP program to illustrate
// Implementation of front() function
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
forward_list<int> myforwardlist{ 1, 2, 3, 4, 5 };
cout << myforwardlist.front();
return 0;
}
Output:
1
forward_list::empty()
empty() function is used to check if the forward list container is empty or not. 检查forward list是否为空。
Syntax :
forwardlistname.empty()
Parameters :
No parameters are passed.
Returns :
True, if list is empty
False, Otherwise
Examples:
Input : forward_list forwardlist{1, 2, 3, 4, 5};
forwardlist.empty();
Output : False
Input : forward_list forwardlist{};
forwardlist.empty();
Output : True
Errors and Exceptions
1. It has a no exception throw guarantee.
2. Shows error when a parameter is passed.
// CPP program to illustrate
// Implementation of empty() function
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
forward_list<int> myforwardlist{};
if (myforwardlist.empty()) {
cout << "True";
}
else {
cout << "False";
}
return 0;
}
Output:
True
Application – front() and empty() : Given a list of integers, find the sum of the all the integers.
Input : 1, 5, 6, 3, 9, 2
Output : 26
Explanation - 1+5+6+3+9+2 = 26
Algorithm :
1. Check if the forward list is empty, if not add the front element to a variable initialised as 0, and pop the front element.
2. Repeat this step until the forward list is empty.
3. Print the final value of the variable.
// CPP program to illustrate
// Application of empty() function
#include <forward_list>
#include <iostream>
using namespace std;
int main()
{
int sum = 0;
forward_list<int> myforwardlist{ 1, 5, 6, 3, 9, 2 };
while (!myforwardlist.empty()) {
sum = sum + myforwardlist.front();
myforwardlist.pop_front();
}
cout << sum;
return 0;
}
Output
26
2 forward_list::unique() in C++ STL
forward_list::unique() is an inbuilt function in C++ STL which removes all consecutive duplicate elements from the forward_list. It uses binary predicate for comparison. forward_list::unique() 删除forward list中连续重复的元素。使用 binary predicate进行比较。
Syntax:
forwardlist_name.unique(BinaryPredicate name)
Parameters: The function accepts a single parameter which is a binary predicate that returns true if the elements should be treated as equal. It has following syntax: 函数参数是 binary predicate 如果元素相等,则返回true。
bool name(data_type a, data_type a)
Return value: The function does not return anything.
// C++ program to illustrate the
// unique() function
#include <bits/stdc++.h>
using namespace std;
// Function for binary_predicate
bool compare(int a, int b)
{
return (abs(a) == abs(b));
}
int main()
{
forward_list<int> list = { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 2, 4, 4 };
cout << "List of elements before unique operation is: ";
// starts from the first element of the list to the last
for (auto it = list.begin(); it != list.end(); ++it)
cout << *it << " ";
// unique operation on forward list
list.unique(compare);
cout << "\nList of elements after unique operation is: ";
// starts from the first element of the list to the last
for (auto it = list.begin(); it != list.end(); ++it)
cout << *it << " ";
return 0;
}
Output:
List of elements before unique operation is: 1 1 1 1 2 2 2 2 3 3 3 2 4 4
List of elements after unique operation is: 1 2 3 2 4
3 forward_list::reverse() in C++ STL
std::forward_list::reverse() is an inbuilt function in CPP STL which reverses the order of the elements present in the forward_list. std::forward_list::reverse() 逆转forward list里所有元素的顺序。
Syntax:
forwardlist_name.reverse()
Parameter: The function does not accept any parameter.
Return value: The function has no return value. It reverses the forward list.
Below program demonstrates the above function:
Program 1:
// C++ program to illustrate the
// reverse() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initialising forward list
forward_list<int> forward = { 10, 20, 40, 30, 70 };
cout << "List elements before performing reverse operation: ";
for (auto it = forward.begin(); it != forward.end(); ++it)
cout << *it << " ";
// Function that performs reverse operation
forward.reverse();
// printing elements of list
cout << "\nList elements after performing reverse operation: ";
for (auto it = forward.begin(); it != forward.end(); ++it)
cout << *it << " ";
return 0;
}
Output:
List elements before performing reverse operation: 10 20 40 30 70
List elements after performing reverse operation: 70 30 40 20 10
4 forward_list::max_size() in C++ STL
std::forward_list::max_size() is an inbuilt function in CPP STL which returns the maximum number of elements can be held by forward_list. This value depends on system or library implementation. std::forward_list::max_size() 返回forward list可以存储的的元素个数。这个值由系统或库决定。
Syntax:
forwardlist_name.max_size ()
Parameters: The function does not accept any parameters.
Return value:The function returns the maximum numbers that can be stored into the forward_list.
Below program demonstrates the above function:
// C++ program to illustrate the
// max_size() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
// initialising the forward list
forward_list<int> f;
// print max number of values that
// can be held by forward_list
cout << "Max_size of the list is "
<< f.max_size() << endl;
return 0;
}
Output:
Max_size of the list is 1152921504606846975
5 Forward List in C++ | Set 1 (Introduction and Important Functions)
Forward list in STL implements singly linked list. Introduced from C++11, forward list are useful than other containers in insertion, removal and moving operations (like sort) and allows time constant insertion and removal of elements.
It differs from list by the fact that forward list keeps track of location of only next element while list keeps track to both next and previous elements, thus increasing the storage space required to store each element. The drawback of forward list is that it cannot be iterated backwards and its individual elements cannot be accessed directly. 和list不同的是,forward list仅跟踪下一个元素的位置,list跟踪前面和后面元素的位置,这就需要增加存储空间保存每个元素。forward list的缺点是无法后向遍历,并且每个元素无法直接访问。
Forward List is preferred over list when only forward traversal is required (same as singly linked list is preferred over doubly linked list) as we can save space. Some example cases are, chaining in hashing, adjacency list representation of graph, etc.
若仅需要前向遍历,那么forward list 比list好,正如singly linked list 比doubly linked list好,可以节省空间。
Operations on Forward List :
1. assign() :- This function is used to assign values to forward list, its another variant is used to assign repeated elements.给forward list 赋值。
// C++ code to demonstrate forward list
// and assign()
#include<iostream>
#include<forward_list>
using namespace std;
int main()
{
// Declaring forward list
forward_list<int> flist1;
// Declaring another forward list
forward_list<int> flist2;
// Assigning values using assign()
flist1.assign({1, 2, 3});
// Assigning repeating values using assign()
// 5 elements with value 10
flist2.assign(5, 10);
// Displaying forward lists
cout << "The elements of first forward list are : ";
for (int&a : flist1)
cout << a << " ";
cout << endl;
cout << "The elements of second forward list are : ";
for (int&b : flist2)
cout << b << " ";
cout << endl;
return 0;
}
Output:
The elements of first forward list are : 1 2 3
The elements of second forward list are : 10 10 10 10 10
2. push_front() :- This function is used to insert the element at the first position on forward list. The value from this function is copied to the space before first element in the container. The size of forward list increases by 1. 在forward list的第一个元素插入元素,函数传来的值复制到容器第一个元素的前面。forward list的大小加1.
3. emplace_front() :- This function is similar to the previous function but in this no copying operation occurs, the element is created directly at the memory before the first element of the forward list. 和第一个函数相似,但是不发生复制,直接的forward list 的第一个元素的前面创建空间。
4. pop_front() :- This function is used to delete the first element of list. 删除list的第一个元素。
// C++ code to demonstrate working of
// push_front(), emplace_front() and pop_front()
#include<iostream>
#include<forward_list>
using namespace std;
int main()
{
// Initializing forward list
forward_list<int> flist = {10, 20, 30, 40, 50};
// Inserting value using push_front()
// Inserts 60 at front
flist.push_front(60);
// Displaying the forward list
cout << "The forward list after push_front operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
// Inserting value using emplace_front()
// Inserts 70 at front
flist.emplace_front(70);
// Displaying the forward list
cout << "The forward list after emplace_front operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
// Deleting first value using pop_front()
// Pops 70
flist.pop_front();
// Displaying the forward list
cout << "The forward list after pop_front operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
return 0;
}
Output:
The forward list after push_front operation : 60 10 20 30 40 50
The forward list after emplace_front operation : 70 60 10 20 30 40 50
The forward list after pop_front operation : 60 10 20 30 40 50
4. insert_after() This function gives us a choice to insert elements at any position in forward list. The arguments in this function are copied at the desired position.在forward list的任何位置的后面插入值。
5. emplace_after() This function also does the same operation as above function but the elements are directly made without any copy operation.
6. erase_after() This function is used to erase elements from a particular position in the forward list.
// C++ code to demonstrate working of
// insert_after(), emplace_after() and erase_after()
#include<iostream>
#include<forward_list>
using namespace std;
int main()
{
// Initializing forward list
forward_list<int> flist = {10, 20, 30} ;
// Declaring a forward list iterator
forward_list<int>::iterator ptr;
// Inserting value using insert_after()
// starts insertion from second position
ptr = flist.insert_after(flist.begin(), {1, 2, 3});
// Displaying the forward list
cout << "The forward list after insert_after operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
// Inserting value using emplace_after()
// inserts 2 after ptr
ptr = flist.emplace_after(ptr,2);
// Displaying the forward list
cout << "The forward list after emplace_after operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
// Deleting value using erase.after Deleted 20
// after ptr
ptr = flist.erase_after(ptr);
// Displaying the forward list
cout << "The forward list after erase_after operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
return 0;
}
Output:
The forward list after insert_after operation : 10 1 2 3 20 30
The forward list after emplace_after operation : 10 1 2 3 2 20 30
The forward list after erase_after operation : 10 1 2 3 2 30
7. remove() :- This function removes the particular element from the forward list mentioned in its argument.删除特定值的所有元素。
8. remove_if() :- This function removes according to the condition in its argument.删除符合条件的所有元素。
// C++ code to demonstrate working of remove() and
// remove_if()
#include<iostream>
#include<forward_list>
using namespace std;
int main()
{
// Initializing forward list
forward_list<int> flist = {10, 20, 30, 25, 40, 40};
// Removing element using remove()
// Removes all occurrences of 40
flist.remove(40);
// Displaying the forward list
cout << "The forward list after remove operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
// Removing according to condition. Removes
// elements greater than 20. Removes 25 and 30
flist.remove_if([](int x){ return x>20;});
// Displaying the forward list
cout << "The forward list after remove_if operation : ";
for (int&c : flist)
cout << c << " ";
cout << endl;
return 0;
}
Output:
The forward list after remove operation : 10 20 30 25
The forward list after remove_if operation : 10 20
9. splice_after() :- This function transfers elements from one forward list to other.
// C++ code to demonstrate working of
// splice_after()
#include<iostream>
#include<forward_list> // for splice_after()
using namespace std;
int main()
{
// Initializing forward list
forward_list<int> flist1 = {10, 20, 30};
// Initializing second list
forward_list<int> flist2 = {40, 50, 60};
// Shifting elements from first to second
// forward list after 1st position
flist2.splice_after(flist2.begin(),flist1);
// Displaying the forward list
cout << "The forward list after splice_after operation : ";
for (int&c : flist2)
cout << c << " ";
cout << endl;
return 0;
}
Output:
The forward list after splice_after operation : 40 10 20 30 50 60
6 Forward List in C++ | Set 2 (Manipulating Functions)
Forward List in C++ | Set 1 (Introduction and Important Functions)
More functions are discussed in this article
Some of the operations other than insertions and deletions that can be used in forward lists are as follows :
1. merge() :- This function is used to merge one forward list with other. If both the lists are sorted then the resulted list returned is also sorted.
2. operator “=” :- This operator copies one forward list into other. The copy made in this case is deep copy.
// C++ code to demonstrate the working of
// merge() and operator=
#include<iostream>
#include<forward_list>
using namespace std;
int main()
{
// Initializing 1st forward list
forward_list<int> flist1 = {1, 2, 3};
// Declaring 2nd forward list
forward_list<int> flist2;
// Creating deep copy using "="
flist2 = flist1;
// Displaying flist2
cout << "The contents of 2nd forward list"
" after copy are : ";
for (int &x : flist2)
cout << x << " ";
cout << endl;
// Using merge() to merge both list in 1
flist1.merge(flist2);
// Displaying merged forward list
// Prints sorted list
cout << "The contents of forward list "
"after merge are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl;
return 0;
}
Output:
The contents of 2nd forward list after copy are : 1 2 3 The contents of forward list after merge are : 1 1 2 2 3 3
3. sort() :- This function is used to sort the forward list.
4. unique() :- This function deletes the multiple occurrences of a number and returns a forward list with unique elements. The forward list should be sorted for this function to execute successfully.
// C++ code to demonstrate the working of
// sort() and unique()
#include<iostream>
#include<forward_list> // for sort() and unique()
using namespace std;
int main()
{
// Initializing 1st forward list
forward_list<int> flist1 = {1, 2, 3, 2, 3, 3, 1};
// Sorting the forward list using sort()
flist1.sort();
// Displaying sorted forward list
cout << "The contents of forward list after "
"sorting are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl;
// Use of unique() to remove repeated occurrences
flist1.unique();
// Displaying forward list after using unique()
cout << "The contents of forward list after "
"unique operation are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl;
return 0;
}
Output:
The contents of forward list after sorting are : 1 1 2 2 3 3 3 The contents of forward list after unique operation are : 1 2 3
5. reverse() :- This function is used to reverse the forward list.
6. swap() :- This function swaps the content of one forward list with other.
// C++ code to demonstrate the working of
// reverse() and swap()
#include<iostream>
#include<forward_list> // for reverse() and swap()
using namespace std;
int main()
{
// Initializing 1st forward list
forward_list<int> flist1 = {1, 2, 3,};
// Initializing 2nd forward list
forward_list<int> flist2 = {4, 5, 6};
// Using reverse() to reverse 1st forward list
flist1.reverse();
// Displaying reversed forward list
cout << "The contents of forward list after"
" reversing are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl << endl;
// Displaying forward list before swapping
cout << "The contents of 1st forward list "
"before swapping are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl;
cout << "The contents of 2nd forward list "
"before swapping are : ";
for (int &x : flist2)
cout << x << " ";
cout << endl;
// Use of swap() to swap the list
flist1.swap(flist2);
// Displaying forward list after swapping
cout << "The contents of 1st forward list "
"after swapping are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl;
cout << "The contents of 2nd forward list "
"after swapping are : ";
for (int &x : flist2)
cout << x << " ";
cout << endl;
return 0;
}
Output:
The contents of forward list after reversing are : 3 2 1 The contents of 1st forward list before swapping are : 3 2 1 The contents of 2nd forward list before swapping are : 4 5 6 The contents of 1st forward list after swapping are : 4 5 6 The contents of 2nd forward list after swapping are : 3 2 1
7. clear() :- This function clears the contents of forward list. After this function, the forward list becomes empty.
8. empty() :- This function returns true if the list is empty otherwise false.
// C++ code to demonstrate the working of
// clear() and empty()
#include<iostream>
#include<forward_list> // for clear() and empty()
using namespace std;
int main()
{
// Initializing forward list
forward_list<int> flist1 = {1, 2, 3,};
// Displaying forward list before clearing
cout << "The contents of forward list are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl;
// Using clear() to clear the forward list
flist1.clear();
// Displaying reversed forward list
cout << "The contents of forward list after "
<< "clearing are : ";
for (int &x : flist1)
cout << x << " ";
cout << endl;
// Checking if list is empty
flist1.empty() ? cout << "Forward list is empty" :
cout << "Forward list is not empty";
return 0;
}
Output:
The contents of forward list are : 1 2 3 The contents of forward list after clearing are : Forward list is empty Recent articles on forward_list
This article is contributed by Manjeet Singh .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.