迭代过程中删除指定元素
总结在迭代过程删除list中指定元素的4种方法
方法1
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> lst = {1,2,3,4,5};
auto it = lst.begin();
while(it != lst.end()) {
if (*it == 4) {
it = lst.erase(it);
} else {
++it;
}
}
for (auto i : lst) {
cout << i << " ";
}
cout << endl;
}
方法2
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> lst = {1,2,3,4,5};
lst.remove_if([](int n) {return n == 4;});
for (auto i : lst) {
cout << i << " ";
}
cout << endl;
}
方法3
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main() {
list<int> lst = {1,2,3,4,5};
lst.erase(std::remove_if(lst.begin(), lst.end(), [](int n) {
return n == 4;
}), lst.end());
for (auto i : lst) {
cout << i << " ";
}
cout << endl;
}
方法4
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> lst = {1,2,3,4,5};
for (auto it = lst.begin(); it != lst.end(); ++it) {
if (*it == 4) {
it = lst.erase(it);
--it;
}
}
for (auto i : lst) {
cout << i << " ";
}
cout << endl;
}