首页 > 解决方案 > C++中向量的分段错误错误

问题描述

以下程序中的错误是什么?该程序用于查找特殊整数,当从向量中删除时将形成这样一个向量,其中奇数索引处的元素之和将等于偶数索引处的元素之和。我知道以下代码可以优化,但我使用了蛮力并得到指定的错误:(

  #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);
    }

它说 :

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

标签: c++11vector

解决方案


这是导致错误的原因。

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

这将解决它!

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


推荐阅读