#include#include
int main() { std::list lst = {1, 2, 3, 4, 5}; auto it = lst.begin(); // iterator to 1st element ++it; // advance iterator to 2nd element lst.erase(it); // erase the 2nd element (with value 2) for (auto& x : lst) std::cout << x << ' '; // Output: 1 3 4 5 return 0; }
#include#include
int main() { std::list lst = {1, 2, 3, 4, 5}; auto it1 = lst.begin(); // iterator to 1st element auto it2 = lst.end(); // iterator to last (i.e., one-past-the-last) element --it2; // move iterator to last element lst.erase(it1, it2); // erase all elements except the first for (auto& x : lst) std::cout << x << ' '; // Output: 1 return 0; }
#includeThe `list::erase()` function is part of the C++ Standard Library and is defined in the `#include
int main() { std::list lst = {1, 2, 3, 4, 5}; lst.erase(lst.begin(), lst.end()); // erase all elements std::cout << lst.empty(); // Output: 1 (true) return 0; }