总结在迭代过程删除list中指定元素的4种方法
方法1#include方法2#include using namespace std; int main() { list
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; }
#include方法3#include using namespace std; int main() { list
lst = {1,2,3,4,5}; lst.remove_if([](int n) {return n == 4;}); for (auto i : lst) { cout << i << " "; } cout << endl; }
#include方法4#include #include using namespace std; int main() { list
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; }
#include#include using namespace std; int main() { list
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; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)