1

I'm quite new to stl's. Could someone let me know what is happening here ? why would the below code seg fault at l.erase(i); . I hope to see the modified list l in main since i pass the list by reference. What is wrong here ?

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

void erase (list<int> &l,int v){
    list<int>::iterator i=l.begin();
    for(;i!=l.end();++i){
        if(*i==v)
            l.erase(i);
    }
}

int main()
{
    list <int> a;
    a.push_back(4);
    a.push_back(5);
    a.push_back(6);
    list<int>::iterator i=a.begin();
    for(;i!=a.end();++i) cout << *i << " ";
    erase(a,5);
    cout << "\nafter:\n";
    list<int>::iterator j=a.begin();
    for(;j!=a.end();++j) cout << *j << " ";
}
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70
shwink
  • 309
  • 2
  • 12
  • Instead of the loop you could just use the [`std::list::remove`](https://en.cppreference.com/w/cpp/container/list/remove) member function. `l.remove(v);` will erase all elements with that value. – Blastfurnace Oct 05 '18 at 03:38
  • Thank you Blastfurnace, i found out from the link why wouldn't the erase work here and yes i knew we could use remove , but was keen on knowing why not erase. Thanks anyway. – shwink Oct 05 '18 at 03:51

0 Answers0