list.remove_if()函数的示例| C ++ STL
示例
这里,我们有一个整数列表,并根据以下给定的测试条件执行删除操作:
删除所有负元素
删除所有可被11整除的元素
删除所有大于20的元素
程序:
#include <iostream>
#include <list>
using namespace std;
//显示列表的功能
void dispList(list<int> L)
{
//在列表中声明迭代器
list<int>::iterator l_iter;
for (l_iter = L.begin(); l_iter != L.end(); l_iter++)
cout<< *l_iter<< " ";
cout<<endl;
}
int main(){
//声明列表
list<int> iList = {10, 20, 11, 22, 21, -10, -20, 13, 55, 44};
//打印列表元素
cout<<"List elements are"<<endl;
dispList(iList);
//只删除负数
iList.remove_if([](int n) {return (n<0); });
cout<<"删除负面元素后列出元素"<<endl;
dispList(iList);
//删除可被11整除的元素
iList.remove_if([](int n) {return (n%11==0); });
cout<<"将除数除以11后列出元素"<<endl;
dispList(iList);
//删除大于20的元素
iList.remove_if([](int n) {return (n>20); });
cout<<"删除大于20后列出元素"<<endl;
dispList(iList);
return 0;
}输出结果
List elements are 10 20 11 22 21 -10 -20 13 55 44 删除负元素后列出元素 10 20 11 22 21 13 55 44 将除数除以11后列出元素 10 20 21 13 删除大于20后列出元素 10 20 13