How does sort function works in algorithm in C++, and how to improve this code? -


here homework challenge:

question: write program prom night, in girl can dance taller boy.

what trying do:

  • b no. of boys, g no. of girls
  • stored in vector
  • sort vector
  • compare heights , result like

      boy      girl     can dance? 1 98       90       yes 2 90       91       no 3 85       82       yes 4 78       75       yes 5 70       72       no 

what want know:

  • how can improve code.
  • how sort function works? type of sorting uses? can applied on arrays well?

my code:

#include <iostream> #include <vector> #include <algorithm>  using namespace std;  int main() {     int b,g,i,j,h,r,count=0;     vector<int> boys, girls;     //input -no. of boys , girls , heights     cout<<"enter number of boys: ";     cin>>b;     cout<<"enter number of girls: ";     cin>>g;     if(g>b)     {         cout<<endl<<"no! girls can't dance, because no. of boys less'";         exit(1);     }     r=b-g;     cout<<endl<<"start entering height of each boy in centimeter...."<<endl;     for(i=0;i<b;i++)     {         cout<<"height of boy "<<i+1<<" : ";         cin>>h;         boys.push_back(h);     }      cout<<endl<<"start entering height of each girl in centimeter...."<<endl;     for(i=0;i<g;i++)     {         cout<<"height of girl "<<i+1<<" : ";         cin>>h;         girls.push_back(h);     }      //sorting heights of boys , girls     //boy     cout<<endl<<"after sorting boys according height"<<endl;     sort(boys.begin(),boys.end(),greater<int>());     for(i=0;i<b;i++)     {         cout<<"height of boy "<<i+1<<" : "<<boys[i]<<endl;     }     //girl     cout<<endl<<"after sorting girls according height"<<endl;     sort(girls.begin(),girls.end(),greater<int>());     for(i=0;i<g;i++)     {         cout<<"height of girl "<<i+1<<" : "<<girls[i]<<endl;     }      for(i=0;i<g;i++)     {         for(j=0;j<boys.size();j++)         {             if(boys.at(i)<=girls.at(i))             {                 count++;             }         }        }      if(count==0)     {         cout<<endl<<"all girls can dance!\nwhile "<<r<<" boys won't have partner!";     }     else     {         cout<<"all girls can't dance!";     }  return 0; } 

it looks issue in line:

for(i=0;i<rem.back();i++) 

rem.back() retrieving last element of rem vector, storing indices. see the documentation on vector.back().

what should have on line this:

for(i = 0; < rem.size(); i++) 

that should help. don't know if fix problems, that's 1 thing noticed.


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -