stl list 删除元素
list.remove()和list.remove_if()函数 (list.remove() and list.remove_if() functions)
remove() function is used to remove all occurrences of a given element from the list and function remove_if() is used to remove set of some specific elements from the list.
remove()函数用于从列表中删除所有出现的给定元素,而remove_if()函数用于从列表中删除某些特定元素的集合。
Example:
例:
List elements are
11
22
33
44
55
11
22
Element to remove: 11
List element after removing 11
22
33
44
55
22
Condition to remove some specific elements: all ODD numbers
List element after removing all ODD numbers
22
44
22
Program:
程序:
#include <iostream>
#include <list>
using namespace std;
int main()
{
//declaring a list
list<int> iList = {11, 22, 33, 44, 55, 11, 22};
//declaring iterator to the list
list<int>::iterator l_iter;
//printing list elements
cout<<"List elements are"<<endl;
for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
cout<< *l_iter<<endl;
//remove 11 from the List
iList.remove(11);
cout<<"List elements after removing 11"<<endl;
for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
cout<< *l_iter<<endl;
//remove all ODD numbers
iList.remove_if([](int n){return (n%2!=0); });
cout<<"List elements after removing all ODD numbers"<<endl;
for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++)
cout<< *l_iter<<endl;
return 0;
}
Output
输出量
List elements are
11
22
33
44
55
11
22
List elements after removing 11
22
33
44
55
22
List elements after removing all ODD numbers
22
44
22
翻译自: https://www.includehelp.com/stl/remove-all-occurrences-of-an-element-and-remove-set-of-some-specific-from-the-list.aspx
stl list 删除元素