how can I delete every second element from std::list in cpp?

  • A+
Category:Languages

I'm trying to delete every second element from std::list but I'm getting segment error (core dump) when I run erase().

#include <bits/stdc++.h>  using namespace std;  int main() {     list <int> num_list;     list <int> :: iterator it;     num_list.push_back(1);     num_list.push_back(2);     num_list.push_back(3);     num_list.push_back(4);     num_list.push_back(5);     cout << num_list.size() << endl;     it = num_list.begin();     advance(it, 1);     for(it; it != num_list.end(); advance(it, 2)) {         num_list.erase(it);     }     for(it = num_list.begin(); it != num_list.end(); ++it) {         cout << *it << " ";     }      cout << endl;     return 0; } 

 


Start from the second item: next(num_list.begin(), 1). The erase method returns an iterator to the next item of the removed item. So you can use just ++ operator to step 2.

int main() {     list<int> num_list;     num_list.push_back(1);     num_list.push_back(2);     num_list.push_back(3);     num_list.push_back(4);     num_list.push_back(5);     cout << num_list.size() << endl;      for (auto it = next(num_list.begin(), 1); it != num_list.end();) {         it = num_list.erase(it);         if (it != num_list.end())             ++it;     }     for (auto it = num_list.begin(); it != num_list.end(); ++it) {         cout << *it << " ";     }     cout << endl;     return 0; } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: