c++ - What can be a possible reason for segmentation fault in this piece of code? -


basically, following code takes input n pairs, each of them having 2 parts, a , b. sorted entire vector using custom comparator, puts values first have higher second value (b) and, if b same, have higher a value. here code,

#include <iostream> #include <utility> #include <vector> using namespace std;  struct mycomp {     bool operator() (const pair<int,int> &p1, const pair<int,int> &p2)     {         if (p1.second > p2.second)  // here              return true;         else if (p1.second == p2.second && p1.first >= p2.first)             return true;         else             return false;     } };  int main (void) {     int i,n,a,b,foo;     cin>>n;     = n;     vector<pair<int,int> > myvec;     while ( != 0 )     {         cin>>a>>b;         myvec.push_back(make_pair(a,b));         i--;     }     int val = 0;     sort(myvec.begin(),myvec.end(),mycomp());     val = val + myvec[0].first;     int k = myvec[0].second;     foo = 1;     while ( k!=0 && foo < n)   // part calculates values have print.      {         //k--;         val = val + myvec[foo].first;         k = k + myvec[foo].second;         k--;         foo++;     }     cout<<val<<"\n";      return 0; } 

on executing this, 100 input, , following being pairs, gives seg fault. tried running through debugger, , says, exc_bad_access (code=1,address=0x101800004) on line marked (here) in code. doing wrong in this?

here link input file: https://www.dropbox.com/s/79ygx4qo5qc8tsl/input.txt?dl=0

your function compare 2 pairs faulty. if 2 of pairs have same a , b, sort never complete.

change to:

struct mycomp {     bool operator() (const pair<int,int> &p1, const pair<int,int> &p2)     {        if ( p1.second != p2.second )           return p1.second > p2.second;        else           return p1.first > p2.first;     } }; 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -