mercredi 13 juillet 2022

terminate called after throwing an instance of 'std::bad_alloc' and signal: aborted (core dumped) [duplicate]

The code is giving me the following error for the input

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool func(pair<string, int> a, pair<string, int> b) {
    if(a.second > b.second) {
        return true;
    } else if (a.second == b.second) {
        if(a.first > b.first) {
            return false;
        }
        return true;
    }
    return false;
}


vector<pair<string, int>> sortMarks(vector<pair<string, int>> v, int N){
    
    
    sort(v.begin(), v.end(), func);
    return v;
}



// Driver code
int main() {
    
    int testcase = 1;
    
    while(testcase--){
        int N;
        cin >> N;
        
        // Declaring vector
        vector<pair<string, int>> v;
        
        // Taking input to vector
        for(int i = 0;i<N;i++){
            string s;
            cin >> s;
            int k;
            cin >> k;
            v.push_back(make_pair(s, k));
        }
        
        v = sortMarks(v, N);
        
        // Printing student name with their marks
        for(auto it = v.begin(); it!=v.end();it++){
            cout << it->first << " " << it->second << endl;
        }
        
    }
    
    return 0;
}  

Error

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
signal: aborted (core dumped)

But if I am using the following implementation of func it is not giving me any error.

bool func(pair<string, int> p1, pair<string, int> p2){
    if(p1.second == p2.second){
        return p1.first < p2.first;
    }
    else
    return p1.second > p2.second;
}

Can anyone please explain this?

Aucun commentaire:

Enregistrer un commentaire