jeudi 4 juin 2020

Cplusplus code to find the number of largest element occurrences gives segmentation error

I want to write a function in c++ which takes a vector array as a parameter and then finds the number of occurrences of the largest value in it. I have written my function birthdaycakecandles and the main function as follows.

#include <iostream>
using namespace std;
int birthdaycakecandles(vector<int> a)
{
    int largest=a[0];
    int pos;
    for(int i=1;i<a.size();++i)
    {
        if(largest<a[i])
        {
            largest=a[i];
            pos=i;
        }
    }
    int count=1;
    for(int i=0;i<a.size();++i)
    {
        if(a[i]==largest&&i!=pos)
        count++;
    }
    return count;
}
int main()
{
    double n;
    cin>>n;
    vector<int> a;
    for(double i=0;i<n;++i)
    cin>>a[i];
    int val=birthdaycakecandles(a);
    cout<<val;
    return 0;
}

Please see this code and tell me what is the error. I am getting segmentation error by the compiler. Please help.

Aucun commentaire:

Enregistrer un commentaire