-1

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
  • 1
    That's not an unknown error. You have memory management issues. – Tanveer Badar Sep 06 '20 at 07:17
  • 1
    C tag removed. Please note that C and C++ are different languages. – kaylum Sep 06 '20 at 07:18
  • 1
    Unrelated 1: [Why should I not `#include `?](https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.) – Ted Lyngmo Sep 06 '20 at 07:19
  • 1
    Unrelated 2: [Why is `using namespace std;` considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Ted Lyngmo Sep 06 '20 at 07:20

1 Answers1

3

This here is causing the error.

temp.erase(A.begin()+i);

This will fix it!!

temp.erase(temp.begin()+i);

Dhruva-404
  • 168
  • 2
  • 10