[英]Debug Assertion Fail (vector subscript out of range)
I found that my result.push_back(make_pair(a[i], b[j]));
我发现我的
result.push_back(make_pair(a[i], b[j]));
, which causing this error but i dont know why (i don't even access vector<pair<int,int>>result;
) ,这导致了这个错误,但我不知道为什么(我什至不访问
vector<pair<int,int>>result;
)
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<utility>
using namespace std;
void input(int n,vector<int>&a) {
int temps;
for (int i = 0; i < n; i++) {
cin >> temps;
a.push_back(temps);
}
}
int main() {
//input
long n, m;
cin >> n; //6
vector<int>a, b;
input(n, a); //{2 5 4 1 7 5}
cin >> m; //7
input(m, b); //{2 3 1 3 2 4 6}
//algorithm
long max = *max_element(a.begin(), a.end()) + *max_element(b.begin(), b.end());
long min = *min_element(a.begin(), a.end()) + *min_element(b.begin(), b.end());
vector<pair<int, int>>result;
int possible = max, plate = 0;
for (int check = max; check >= min; check--) {
int j = 0, i = 0, plate2 = 0;
for (; i < a.size(); i++) {
if (a[i] >= check) {}
else {
if (j > b.size() - 1) { break; }
if (a[i] + b[j] >= check) {
j++; plate2++;
result.push_back(make_pair(a[i], b[j]));
}
else {
i--; j++;
}
}
}
if (i > a.size() - 1) { possible = check; plate = plate2; break; }
}
cout << possible << " " << plate << endl; //5 3
return 0;
}
if you remove the line result.push_back(make_pair(a[i],b[j]);
, there is no error message anymore, so i think i'm not access wrong a[i] and b[j] elements如果删除行
result.push_back(make_pair(a[i],b[j]);
,则不再有错误消息,所以我认为我不会访问错误的 a[i] 和 b[j] 元素
if (j > b.size() - 1) { break; } //(1)
if (a[i] + b[j] >= check) { //(2)
j++; plate2++; // HERE IS YOUR PROBLEM (3)
result.push_back(make_pair(a[i], b[j])); //(4)
Assume that j == b.size()-1
at the beginning.假设开始时
j == b.size()-1
。 The if (j > b.size() - 1)
clause is false, so the loop does not break
. if (j > b.size() - 1)
子句为假,因此循环不会break
。 It continues with (2), which is okay.它继续(2),这没关系。 In (3) you add +1 to j, so now
j == b.size()
.在 (3) 中,您将 +1 添加到 j,因此现在
j == b.size()
。 In (4) you try to access b[j]
, which is now b[b.size()]
, which is invalid, as indizes start at 0.在 (4) 中,您尝试访问
b[j]
,现在是b[b.size()]
,这是无效的,因为 indizes 从 0 开始。
IOW: You tried to assure that j never points beyond the number of valid elements, but then you increment j after that test and access invalid memory. IOW:您试图确保 j 永远不会超过有效元素的数量,但是在该测试之后您增加了 j 并访问了无效内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.