dimanche 6 septembre 2020

The code that i have written is giving me unknown error. What kind of error is this and how to fix it?

What's the error in the following program ? The Program is for finding special integer which when removed from the vector will form such a vector where the sum of element at odd index will be equal to sum of element at even index.I know the following code can be optimized but i used brute force and getting the error as specified :(

  #include<bits/stdc++.h>
    using namespace std;
    int solve(vector<int> &A) {
        
        for(int i=0;i<A.size();i++){
            
            vector<int>temp;
            temp = A;
            temp.erase(A.begin()+i);
            cout << "Size of temp after erase is : " << temp.size() << endl;
            
            int evenSum = 0, oddSum = 0;
                
            for(int k = 0;k<temp.size();k++) 
            {
                if(k%2 == 0)
                {
                    evenSum = evenSum + temp[k];
                    cout << "Adding to Even Sum : " << temp[k] << endl;
                }
                else
                { 
                    oddSum = oddSum + temp[k];
                    cout << "Adding to Odd Sum : " << temp[k] << endl;
                }
            }
            
            cout << evenSum << " " << oddSum << endl;
            
            if(evenSum == oddSum){
                return A[i];
            }
        }
    }
    int main(){
        vector<int> v =  {2, 1, 6, 4};
        cout << solve(v);
    }

It says :

 *** Error in `./a.out': double free or corruption (out): 0x0000000001428c40 ***                                                             
    Aborted

Aucun commentaire:

Enregistrer un commentaire