segmentation fault whne using list::remove_if

I am trying out the stl concepts and started facing the segmentation fault when using remove_if of list.
Following is the code I was trying. i am not compeletely sure if the usage of remove_if is done correctly.
Please help me in understandin what is wrong with the code and also if the usage of remove_if is correct.(i see many using operator() for remove_if but i dont understand why)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<iostream>
        #include<list>
        using namespace std;

        struct data
        {
         int a, b;

          static bool compare(struct data first, struct data sec)
          {
           if(first.a < sec.a)
             return true;
           else return false;
          }

          static bool rmv(struct data it)
          {
           if(it.a == 10)
             return true;
           else return false;
          }
        };
        std::list<data> table;

        void runn();

        void runn()
        {
        struct data a1,b2,c3,d4;
        a1.a = 10;
        a1.b = 5;
        b2.a = 20;
        b2.b = 2;
        c3.a = 30;
        c3.b = 3;
        d4.a = 40;
        d4.b = 4; 

        table.push_front(a1);
        table.push_front(b2);
        table.push_front(c3);
        table.push_front(d4);

        table.sort(data::compare);
        std::list<data>::iterator i;
        for( i = table.begin(); i != table.end(); ++i)
           cout << " " << i->a << " " << i->b << endl;
        for( i = table.begin(); i != table.end(); ++i)
           table.remove_if(data::rmv);
        for( i = table.begin(); i != table.end(); ++i)
           cout << " " << i->a << " " << i->b << endl;
        }
        int main()
        {
          runn();
          return 0;
        }
         


the output :

10 5
20 2
30 3
40 4
Segmentation fault
I believe the problem is that you're modifying(deleting items) the container in your loop, which invalidates the iterator. Basically once you call remove_if, i is no longer valid and can't be used unless it's reset.

Anyway you don't need to loop. remove_if will remove all elements that match your predicate.
thanks spaggy for the reply..

got it..
At first i did not understand the proper useage of remove_if..
Last edited on
The member function remove_if removes all elements of a list that satisfy the predicate.

So you shall not use the loop. It was enough to write

table.remove_if(data::rmv);
Last edited on
Topic archived. No new replies allowed.