List in C++ Standard Template Library (STL)

Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about doubly linked list. For implementing a singly linked list, we use forward list. 列表是序列容器,允许内存非连续存储。和vector相比,list的遍历更慢,但是找到位置时,插入和删除比较快。通常说的列表是doubly linked list双向链表,实现一个简单的列表,用前向列表。

Below is the program to show the working of some functions of List:

#include <iostream> 
#include <list> 
#include <iterator> 
using namespace std; 

//function for printing the elements in a list 
void showlist(list <int> g) 
{ 
	list <int> :: iterator it; 
	for(it = g.begin(); it != g.end(); ++it) 
		cout << '\t' << *it; 
	cout << '\n'; 
} 

int main() 
{ 

	list <int> gqlist1, gqlist2; 


	for (int i = 0; i < 10; ++i) 
	{ 
		gqlist1.push_back(i * 2); 
		gqlist2.push_front(i * 3); 
	} 
	cout << "\nList 1 (gqlist1) is : "; 
	showlist(gqlist1); 

	cout << "\nList 2 (gqlist2) is : "; 
	showlist(gqlist2); 

	cout << "\ngqlist1.front() : " << gqlist1.front(); 
	cout << "\ngqlist1.back() : " << gqlist1.back(); 

	cout << "\ngqlist1.pop_front() : "; 
	gqlist1.pop_front(); 
	showlist(gqlist1); 

	cout << "\ngqlist2.pop_back() : "; 
	gqlist2.pop_back(); 
	showlist(gqlist2); 

	cout << "\ngqlist1.reverse() : "; 
	gqlist1.reverse(); 
	showlist(gqlist1); 

	cout << "\ngqlist2.sort(): "; 
	gqlist2.sort(); 
	showlist(gqlist2); 

	return 0; 

} 

The output of the above program is :

List 1 (gqlist1) is :     0    2    4    6    
8    10    12    14    16    18

List 2 (gqlist2) is :     27    24    21    18    
15    12    9    6    3    0

gqlist1.front() : 0
gqlist1.back() : 18
gqlist1.pop_front() :     2    4    6    8    
10    12    14    16    18

gqlist2.pop_back() :     27    24    21    18    
15    12    9    6    3

gqlist1.reverse() :     18    16    14    12    
10    8    6    4    2

gqlist2.sort():     3    6    9    12    
15    18    21    24    27

1 list front() function in C++ STL

The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. 函数 list::front()获得list容器的第一个元素的引用,和list::begin()不同,这个函数获得list容器的第一个元素的引用。

Syntax:

list_name.front() 

Parameters: This function does not accept any parameter, it simply returns a reference to the first element in the list container.调用不需要参数。

Return Value: This function returns a direct reference to the first element in the list container.直接返回第一个元素的直接引用。

Exception: This function creates an undefined behavior when used with an empty list container. 

Below program illustrates the list::front() function.

// CPP program to illustrate the 
// list::front() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Creating a list 
	list<int> demoList; 

	// Add elements to the List 
	demoList.push_back(10); 
	demoList.push_back(20); 
	demoList.push_back(30); 
	demoList.push_back(40); 

	// get the first element using front() 
	int ele = demoList.front(); 

	// Print the first element 
	cout << ele; 

	return 0; 
} 

Output:

10

Note: This function works in constant time complexity.

2 list back() function in C++ STL

The list::back() function in C++ STL returns a direct reference to the last element in the list container. This function is different from the list::end() function as the end() function returns only the iterator to the last element. 函数list::back()  获得list容器的最后一个元素的直接引用。和 list::end()不同,end()是返回最后一个元素的迭代器。

Syntax:

list_name.back() 

Parameters: This function does not accepts any parameter.不需要参数

Return Value: This function returns a direct reference to the last element in the list container demo_list.

Exception: There is as no such exception in this function but calling this function on an empty list container creates an undefined behavior in C++.

Below program illustrates the list::back() function.

// CPP program to illustrate the 
// list::assign() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Initialization of list 
	list<int> demo_list; 

	// Adding elements to the list 
	demo_list.push_back(10); 
	demo_list.push_back(20); 
	demo_list.push_back(30); 

	// prints the last element of demo_list 
	cout << demo_list.back(); 

	return 0; 
} 

Output:

30

3 list push_front() function in C++ STL

The list::push_front() is a built-in function in C++ STL which is used to insert an element at the front of a list container just before the current top element. This function also increases the size of the container by 1. 函数list::push_front() 在list容器的前面插入一个元素,即当前最上面的元素,这个函数也让容器的大小加1.

Syntax:

list_name.push_front(dataType value)

Parameters: This function accepts a single parameter value. This parameter represents the element which is needed to be inserted at the front of the list container.需要插入的元素,插在list容器的前面

Return Value: This function does not return anything.

Below program illustrate the list::push_front() function in C++ STL:

// CPP program to illustrate the 
// list::push_front() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Creating a list 
	list<int> demoList; 

	// Adding elements to the list 
	// using push_back() 
	demoList.push_back(10); 
	demoList.push_back(20); 
	demoList.push_back(30); 
	demoList.push_back(40); 

	// Initial List: 
	cout << "Initial List: "; 
	for (auto itr = demoList.begin(); itr != demoList.end(); itr++) 
		cout << *itr << " "; 

	// Adding elements to the front of List 
	// using push_front 
	demoList.push_front(5); 

	// List after adding elements to front 
	cout << "\n\nList after adding elements to the front:\n"; 
	for (auto itr = demoList.begin(); itr != demoList.end(); itr++) 
		cout << *itr << " "; 

	return 0; 
} 

Output:

Initial List: 10 20 30 40 

List after adding elements to the front:
5 10 20 30 40

4 list push_back() function in C++ STL

The list:push_back() function in C++ STL is used to add a new element to an existing list container. It takes the element to be added as a parameter and adds it to the list container. 函数list:push_back() 在list容器的尾部插入元素。

Syntax:

list_name.push_back(value) 

Parameters: This function accepts a single parameter which is mandatory value. This refers to the element needed to be added to the list, list_name.

Return Value: The return type of this function is void and it does not returns any value.

Below program illustrates the list::push_back() function.

// CPP program to illustrate the 
// list::push_back() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Initialization of list 
	list<int> demo_list; 

	// intital size of list 
	cout << "Initial Size of the list: "
		<< demo_list.size() << endl; 

	// Adding elements to the list 
	// using push_back function 
	demo_list.push_back(10); 
	demo_list.push_back(20); 
	demo_list.push_back(30); 

	// Size of list after adding 
	// some elements 
	cout << "Size of list after adding three "
		<< "elements: " << demo_list.size(); 

	return 0; 
} 

Output:

Initial Size of the list: 0
Size of list after adding three elements: 3

5 list pop_front() function in C++ STL

The list::pop_front() is a built-in function in C++ STL which is used to remove an element from the front of a list container. This function thus decreases the size of the container by 1 as it deletes the element from the front of a list. 函数 list::pop_front()  删除list容器最前面的元素,导致容器的大小减1. 

Syntax:

list_name.pop_front();

Parameters: The function does not accept any parameter.

Return Value: This function does not returns anything.

Below program illustrate the list::pop_front() function in C++ STL:

// CPP program to illustrate the 
// list::pop_front() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Creating a list 
	list<int> demoList; 

	// Adding elements to the list 
	// using push_back() 
	demoList.push_back(10); 
	demoList.push_back(20); 
	demoList.push_back(30); 
	demoList.push_back(40); 

	// Initial List: 
	cout << "Initial List: "; 
	for (auto itr = demoList.begin(); itr != demoList.end(); itr++) 
		cout << *itr << " "; 

	// removing an element from the front of List 
	// using pop_front 
	demoList.pop_front(); 

	// List after removing element from front 
	cout << "\n\nList after removing an element from front: "; 
	for (auto itr = demoList.begin(); itr != demoList.end(); itr++) 
		cout << *itr << " "; 

	return 0; 
} 

Output:

Initial List: 10 20 30 40 

List after removing an element from front: 20 30 40

6 list pop_back() function in C++ STL

The list::pop_back() is a built-in function in C++ STL which is used to remove an element from the back of a list container. That is, this function deletes the last element of a list container. This function thus decreases the size of the container by 1 as it deletes an element from the end of list. 函数 list::pop_back() 删除list容器的尾部的元素,删除最后一个元素,导致容器大小减1

Syntax:

list_name.pop_back();

Parameters: The function does not accept any parameter.

Return Value: This function does not returns anything.

Below program illustrate the list::pop_back() function in C++ STL:

// CPP program to illustrate the 
// list::pop_back() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Creating a list 
	list<int> demoList; 

	// Adding elements to the list 
	// using push_back() 
	demoList.push_back(10); 
	demoList.push_back(20); 
	demoList.push_back(30); 
	demoList.push_back(40); 

	// Initial List: 
	cout << "Initial List: "; 
	for (auto itr = demoList.begin(); itr != demoList.end(); itr++) 
		cout << *itr << " "; 

	// removing an element from the end of List 
	// using pop_back 
	demoList.pop_back(); 

	// List after removing element from end 
	cout << "\n\nList after removing an element from end: "; 
	for (auto itr = demoList.begin(); itr != demoList.end(); itr++) 
		cout << *itr << " "; 

	return 0; 
} 

Output:

Initial List: 10 20 30 40 

List after removing an element from end: 10 20 30

7 list::begin() and list::end() in C++ STL


Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. 容器list用来存储非连续数据,array和vector都是连续的。

list::begin()

begin() function is used to return an iterator pointing to the first element of the list container. It is different from the front() function because the front function returns a reference to the first element of the container but begin() function returns a bidirectional iterator to the first element of the container.函数begin()返回指向list容器的第一个元素的迭代器,和front()不同,front返回的是容器的第一个元素的引用。

Syntax :

listname.begin()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the first element.

Examples:

Input  : mylist{1, 2, 3, 4, 5};
         mylist.begin();
Output : returns an iterator to the element 1

Input  : mylist{8, 7};
         mylist.begin();
Output : returns an iterator to the element 8

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 begin() function 
#include <iostream> 
#include <list> 
using namespace std; 

int main() 
{ 
	// declaration of list container 
	list<int> mylist{ 1, 2, 3, 4, 5 }; 

	// using begin() to print list 
	for (auto it = mylist.begin(); it != mylist.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

1 2 3 4 5

Time Complexity : O(1)

list::end()

end() function is used to return an iterator pointing to the last element of the list container. It is different from the back() function because the back() function returns a reference to the last element of the container but end() function returns a bidirectional iterator to the last element of the container. 函数end返回list容器的最后一个元素的迭代器,和back不同,back返回的是容器最后一个元素的引用,

Syntax :

listname.end()
Parameters :
No parameters are passed.
Returns :
This function returns a bidirectional
iterator pointing to the last element.

Examples:

Input  : mylist{1, 2, 3, 4, 5};
         mylist.end();
Output : returns an iterator to the element 5

Input  : mylist{8, 7};
         mylist.end();
Output : returns an iterator to the element 7

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 end() function 
#include <iostream> 
#include <list> 
using namespace std; 

int main() 
{ 
	// declaration of list container 
	list<int> mylist{ 1, 2, 3, 4, 5 }; 

	// using end() to print list 
	for (auto it = mylist.begin(); it != mylist.end(); ++it) 
		cout << ' ' << *it; 
	return 0; 
} 

Output:

1 2 3 4 5

Time Complexity : O(1)

// CPP program to illustrate the 
// list::end() function 
#include <bits/stdc++.h> 
using namespace std; 

int main() 
{ 
	// Creating a list 
	list<int> demoList; 

	// Add elements to the List 
	demoList.push_back(10); 
	demoList.push_back(20); 
	demoList.push_back(30); 
	demoList.push_back(40); 

	// using end() to get iterator 
	// to past the last element 
	list<int>::iterator it = demoList.end(); 

	// This will not print the last element 
	cout << "Returned iterator points to : " << *it << endl; 

	// Using end() with begin() as a range to 
	// print all of the list elements 
	for (auto itr = demoList.begin(); 
		itr != demoList.end(); itr++) { 
		cout << *itr << " "; 
	} 

	return 0; 
} 

Output:

Returned iterator points to : 4
10 20 30 40

Note: This function works in constant time complexity.

8 list::empty() and list::size() in C++ STL


Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.

list::empty()

empty() function is used to check if the list container is empty or not. 检查list容器是否为空。

Syntax :

listname.empty()
Parameters :
No parameters are passed.
Returns :
True, if list is empty
False, Otherwise

Examples:

Input  : list list{1, 2, 3, 4, 5};
         list.empty();
Output : False

Input  : list list{};
         list.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 <iostream> 
#include <list> 
using namespace std; 

int main() 
{ 
	list<int> mylist{}; 
	if (mylist.empty()) { 
		cout << "True"; 
	} 
	else { 
		cout << "False"; 
	} 
	return 0; 
} 

Output:

True

Application :
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 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 list is empty.
  3. Print the final value of the variable.
// CPP program to illustrate 
// Application of empty() function 
#include <iostream> 
#include <list> 
using namespace std; 

int main() 
{ 
	int sum = 0; 
	list<int> mylist{ 1, 5, 6, 3, 9, 2 }; 
	while (!mylist.empty()) { 
		sum = sum + mylist.front(); 
		mylist.pop_front(); 
	} 
	cout << sum; 
	return 0; 
} 

Output:

26

list::size()

size() function is used to return the size of the list container or the number of elements in the list container. 返回容器list的元素的个数。

Syntax :

listname.size()
Parameters :
No parameters are passed.
Returns :
Number of elements in the container.

Examples:

Input  : list list{1, 2, 3, 4, 5};
         list.size();
Output : 5

Input  : list list{};
         list.size();
Output : 0

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 size() function 
#include <iostream> 
#include <list> 
using namespace std; 

int main() 
{ 
	list<int> mylist{ 1, 2, 3, 4, 5 }; 
	cout << mylist.size(); 
	return 0; 
} 

Output:

5

Application :
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 size of the list is 0, if not add the front element to a variable initialised as 0, and pop the front element.
  2. Repeat this step until the list is empty.
  3. Print the final value of the variable.
// CPP program to illustrate 
// Application of size() function 
#include <iostream> 
#include <list> 
using namespace std; 

int main() 
{ 
	int sum = 0; 
	list<int> mylist{ 1, 5, 6, 3, 9, 2 }; 
	while (mylist.size() > 0) { 
		sum = sum + mylist.front(); 
		mylist.pop_front(); 
	} 
	cout << sum; 
	return 0; 
} 

Output:

26

9 list::remove() and list::remove_if() in C++ STL

Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists.

list::remove()

remove() function is used to remove all the values from the list that correspond to the value given as parameter to the function函数remove删除和参数相等的list中所有元素。

Syntax :

listname.remove(value)
Parameters :
The value of the element to be removed is passed as the parameter.
Result :
Removes all the elements of the container
equal to the value passed as parameter

Examples:

Input  : list list{1, 2, 3, 4, 5};
         list.remove(4);
Output : 1, 2, 3, 5

Input  : list list{1, 2, 2, 2, 5, 6, 7};
         list.remove(2);
Output : 1, 5, 6, 7

Errors and Exceptions

  1. Shows error if the value passed doesn’t match the list type.
  2. Shows no exception throw guarantee if the comparison between value and elements of the list feature doesn’t throw any exception.
// CPP program to illustrate 
// Implementation of remove() function 
#include <iostream> 
#include <list> 
using namespace std; 

int main() 
{ 
	list<int> mylist{ 1, 2, 2, 2, 5, 6, 7 }; 
	mylist.remove(2); 
	for (auto it = mylist.begin(); it != mylist.end(); ++it) 
		cout << ' ' << *it; 
} 

Output:

1 5 6 7

list::remove_if()

remove_if() function is used to remove all the values from the list that correspond true to the predicate or condition given as parameter to the function. The function iterates through every member of the list container and removes all the element that return true for the predicate.函数remove_if()删除符合条件的list中所有元素。

Syntax :

listname.remove_if(predicate)
Parameters :
The predicate in the form of aa function pointer
or function object is passed as the parameter.
Result :
Removes all the elements of the container
which return true for the predicate.

Examples:

Input  : list list{1, 2, 3, 4, 5};
         list.remove_if(odd);
Output : 2, 4

Input  : list list{1, 2, 2, 2, 5, 6, 7};
         list.remove_if(even);
Output : 1, 5, 7

Errors and Exceptions

  1. Shows no exception throw guarantee if the predicate function feature doesn’t throw any exception.
// CPP program to illustrate 
// Implementation of remove_if() function 
#include <iostream> 
#include <list> 
using namespace std; 

// Predicate implemented as a function 
bool even(const int& value) { return (value % 2) == 0; } 

// Main function 
int main() 
{ 
	list<int> mylist{ 1, 2, 2, 2, 5, 6, 7 }; 
	mylist.remove_if(even); 
	for (auto it = mylist.begin(); it != mylist.end(); ++it) 
		cout << ' ' << *it; 
}

Output:

1 5 7

Application : Given a list of integers, remove all the prime numbers from the list and print the list.

Input  : 2, 4, 6, 7, 9, 11, 13
Output : 4, 6, 9
// CPP program to illustrate 
// Application of remove_if() function 
#include <iostream> 
#include <list> 
using namespace std; 

// Predicate implemented as a function 
bool prime(const int& value) 
{ 
	int i; 
	for (i = 2; i < value; i++) { 
		if (value % i == 0) { 
			return false; 
			; 
			break; 
		} 
	} 
	if (value == i) { 
		return true; 
		; 
	} 
} 

// Main function 
int main() 
{ 
	list<int> mylist{ 2, 4, 6, 7, 9, 11, 13 }; 
	mylist.remove_if(prime); 
	for (auto it = mylist.begin(); it != mylist.end(); ++it) 
		cout << ' ' << *it; 
} 

Output:

4 6 9

猜你喜欢

转载自blog.csdn.net/qq_27009517/article/details/86522857