-2

I am writing a code to find number of pairs in a given array.But i am getting segmentation fault.

I am sorting the given array and then comparing the elements to get pairs.

#include <bits/stdc++.h>

using namespace std;


int sockMerchant(int n, vector<int> ar) {
sort(&ar[0], &ar[n]);
int k=1;
int m=0;
for(int i=0;i<n;i++){
    for(int j=1;j<n;j++){
        if (ar[i]=ar[j])
        k++;
        if(ar[i]!=ar[j])
        i=j;
        m+=k/2;
        break;
    }
}
return m;
}

int main()
{
    int n;
    cin>>n;
    vector<int> ar;
    for(int i=0;i<n;i++){
        cin>>ar[i];
    }
    int k = sockMerchant(n,ar);
    cout<<k<<endl;
    return 0;
}
  • https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h –  Sep 08 '19 at 13:04

1 Answers1

0

When you say vector<int> ar; It just creates an empty vector. So your for loop is basically trying to write to the elements of an empty vector.

    for(int i=0;i<n;i++){
        cin>>ar[i];
    }

You can either:

  1. Call ar.resize(n); before the for loop

or

  1. You can use vector::push_back function to let the vector resize dynamically as you enter your values.
    for(int i=0;i<n;i++){
        int tmp;
        cin>>tmp;
        ar.push_back(tmp);
    }

P.S: You don't have to pass n to your function. you can use ar.size() to get the size of your vector

Dinesh
  • 449
  • 2
  • 5