Why segmentation fault?

I've written the following code.
When I give
8
2 3 4 4 2 1 3 1

it shows segmentation fault..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
#include<bits/stdc++.h>

using namespace std;

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);

    int n;
    while(cin>>n)
    {
        vector<int>v;

    for(int i=0; i<n; i++)
    {
        int p;
        cin>>p;
        v.push_back(p);
    }

    int co=0;

    for(int i=0; i<n; i++)
    {
        if(v[i]==4)
        {
            co++;
            v.erase(v.begin()+i);
        }
    }

    if(v.size()!=0)
    {
        for(int j=0; j<v.size(); j++)
        {
            for(int k=j+1; k<v.size(); k++)
            {
                if(v[j]+v[k]==4)
                {
                    co++;
                    v.erase(v.begin()+j);
                    v.erase(v.begin()+k);
                }
            }
        }
        cout<<co+v.size()<<endl;
    }
    else
        cout<<co<<endl;
    }

    return 0;
}
if (v[i] == 4)
It blows up when you do that because your vector has 7 elements at this point, and i is 7. Which is bad as the range should be 0 to 6.

What are you trying to achieve?
Last edited on
How do i fix it? @mutexe
What are you trying to achieve?
At line 41 and 42, after you erase these two items, you don't want to increment j because the j'th item is now the new item. Also you want to break out of the k loop once you find a match.

I think you'll find that your code runs too slow when the input is very large. You've made a common mistake: representing the data as it is given to you, rather than in a way that is convenient for your algorithm. For example, consider creating an array of 5 integers. array[n] will be the number of groups with n members. Now with a little arithmetic you can match up groups and get your final answer.
also, you don't really need n:
 
    for(int i=0; i<n; i++)

n is actually v.size()
Topic archived. No new replies allowed.