[英]Handling pointer in vector C++
Having problem using the vector in C++. 在C ++中使用向量时遇到问题。 The following code is having this
Runtime Error :
以下代码具有此运行时错误:
* Error in `./a.out': double free or corruption (out): 0x0000000001e5d050 * === Backtrace: === . *`./a.out'出错:double free或broken(out):0x0000000001e5d050 * === Backtrace:===。 .
。 .
。
I have written this code. 我写了这段代码。
int main(){
vector<int> ve;
int n;
cin>>n;
for(int i=1; i<n+1; i++)ve.push_back(i);
int last, sec_last, ans;
while(!(ve.empty())){
ans = ve.back();
last = ve.back();
ve.pop_back();
sec_last = ve.back();
ve.pop_back();
ve.push_back(last + sec_last + last*sec_last);
}
cout<<"\nline 20\n";
cout<<ans<<"\n";
cout<<"\nline 22\n";
}
Please explain me what does this error mean, and how can I correct it... 请解释一下这个错误是什么意思,我该怎么纠正它...
"Calling back / pop_back on an empty container is undefined" -- Internet “未定义在空容器上调用/ pop_back” - Internet
While loop condition prevents you only once, until the vector ve
is modified again by pop_back
. 虽然循环条件只能阻止你一次,直到
pop_back
再次修改了向量ve
。 In that case there is possibility that vector is empty and calling back
on empty vector will likely result into a crash. 在这种情况下,vector可能是空的,并且
back
空向量可能会导致崩溃。
while(!(ve.empty())){
ans = ve.back();
last = ve.back();
ve.pop_back(); // <---- Vector could become empty
sec_last = ve.back(); // <---- If vector is indeed empty, then undefined behavior
ve.pop_back();
ve.push_back(last + sec_last + last*sec_last);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.