简体   繁体   中英

Debug Assertion Fail (vector subscript out of range)

I found that my 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; )

#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

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. The if (j > b.size() - 1) clause is false, so the loop does not break . It continues with (2), which is okay. In (3) you add +1 to j, so now 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM