【问题标题】:How does sort function works in algorithm in C++, and how to improve this code? [closed]排序函数在 C++ 算法中是如何工作的,以及如何改进这段代码? [关闭]
【发布时间】:2016-08-23 21:35:20
【问题描述】:

这是我的家庭作业挑战:

问题:为一个舞会之夜编写一个程序,其中一个女孩只能和一个高个子的男孩跳舞。

我想做什么:

  • b 没有。男孩,g 没有。的女孩
  • 存储在向量中
  • 对向量进行排序
  • 比较高度并得到类似的结果

      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;
}

【问题讨论】:

  • 你真的应该提供输入、预期输出和你真正得到的。看到你的问题我头疼。
  • @Mukul 你为什么不按照你发布的格式编码输出?
  • 现在变得更糟了......
  • 请不要以使现有答案无效的方式更改您的问题。如果您有新问题但没有找到解决方案,请提出新问题。
  • @MukulChauhan 从现在开始阅读How to Ask 并发布好问题。对于新用户来说,发帖的权利在设计上是一种稀缺资源,试图通过滥用编辑功能来欺骗这种设计是不行的。现在您要么等待,要么尝试自己寻找答案,它可能存在于本网站的某个地方。

标签: c++ algorithm vector


【解决方案1】:

看起来问题出在这一行:

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

rem.back() 正在检索 rem 向量的最后一个元素,该向量存储索引。见the documentation on Vector.back()

你应该在这条线上有这样的东西:

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

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

【讨论】:

    猜你喜欢
    • 2021-02-11
    • 1970-01-01
    • 2013-01-19
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多