如何解决C ++中带有向量的分段错误
以下程序有什么错误?该程序用于查找特殊整数,将其从向量中删除时将形成这样的向量,其中奇数索引处的元素之和等于偶数索引处的元素之和。我知道以下代码可以优化,但我使用了蛮力并得到指定的错误:(
function incrementCounter(counterName){
// Initialize a variable to store the counters object
let counters;
// Safely try to parse the data in localstorage
try {
counters = JSON.parse(localStorage.getItem("counters"));
} catch (er) {
// In case localstorage doesn't have a valid JSON make a new object
counters = {};
}
if(typeof counters[counterName] !== 'number'){
// if the counter is not initialized in the object,initialize it
counters[counterName] = 0;
}
// Now we can safely increment its value in the counters object
counters[counterName]++;
// Now that the value is updated,store it back in localStorage
localStorage.setItem("counters",JSON.stringify(counters));
// Return the updated value of the counter in question
return counters[counterName];
}
它说:
#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);
}
解决方法
这是导致错误的原因。
temp.erase(A.begin()+i);
这将解决它!
temp.erase(temp.begin()+i);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。