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
stl list 删除元素
本文详细介绍了STL list中的remove()和remove_if()函数的使用方法,通过实例展示了如何从列表中删除指定元素及满足特定条件的元素集合。remove()函数用于移除列表中所有给定元素的出现,而remove_if()则可以移除符合预定义条件的元素集合。

被折叠的 条评论
为什么被折叠?



