删除所有出现的元素,并从列表中删除一些特定的元素。C ++ STL
list.remove()和list.remove_if()函数
remove()函数用于从列表中删除所有出现的给定元素,而remove_if()函数用于从列表中删除某些特定元素的集合。
示例
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
程序:
#include <iostream> #include <list> using namespace std; int main() { //声明列表 list<int> iList = {11, 22, 33, 44, 55, 11, 22}; //在列表中声明迭代器 list<int>::iterator l_iter; //打印列表元素 cout<<"List elements are"<<endl; for (l_iter = iList.begin(); l_iter != iList.end(); l_iter++) cout<< *l_iter<<endl; //从列表中删除11- 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; //删除所有奇数 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; }
输出结果
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