c++算法中排序函数是如何工作的,以及如何改进这段代码

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

本文关键字:何改进 代码 段代码 工作 排序 算法 函数 何工作 c++      更新时间:2023-10-16

这是我的作业挑战:

问题:为一个舞会之夜写一个程序,在这个舞会上,一个女孩只能和一个比她高的男孩跳舞

我想做什么:

  • b no。男孩,g no。女孩的
  • 存储于矢量
  • 排序向量
  • 比较高度,得到结果

      Boy      Girl     Can dance?
    1 98       90       Yes
    2 90       91       No
    3 85       82       Yes
    4 78       75       Yes
    5 70       72       No
    

我想知道的:

    如何改进这段代码?
  • 排序函数是如何工作的?它使用什么类型的排序?它也可以应用于数组吗?
我代码:

#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 and girls and their heights
    cout<<"Enter number of Boys: ";
    cin>>b;
    cout<<"Enter number of Girls: ";
    cin>>g;
    if(g>b)
    {
        cout<<endl<<"NO! All girls can't dance, because no. of boys is 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 and girls
    //boy
    cout<<endl<<"After sorting boys according to 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 to 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 a partner!";
    }
    else
    {
        cout<<"All girls can't dance!";
    }
return 0;
}

看起来问题在这一行:

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

rem.back()是检索rem向量的最后一个元素,这是存储索引。参见Vector.back()的文档。

你应该在那行写这样的内容:

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

那应该有帮助。我不知道它是否会解决所有问题,但这是我注意到的一件事。