c++算法中排序函数是如何工作的,以及如何改进这段代码
How does sort function works in algorithm in C++, and how to improve this code?
这是我的作业挑战:
问题:为一个舞会之夜写一个程序,在这个舞会上,一个女孩只能和一个比她高的男孩跳舞
我想做什么:
-
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++)
那应该有帮助。我不知道它是否会解决所有问题,但这是我注意到的一件事。
相关文章:
- 可以使用移动语义更改或改进此C++代码吗?
- 如何改进我的代码,使其不会因超时而终止?(黑客排名挑战)
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- DirectX 11 引擎在第三次代码改进后没有突然运行,我不知道为什么
- 我写了一个类,它总是将其函数参数委托给它的成员,我该如何改进代码
- 如何用逗号分隔输出?如何改进此代码以使其看起来更体面?
- 无论代码长度如何,以下代码的内存要求有何不同?
- 初学者代码寻找改进
- 改进我的代码以应对C++的挑战,新手在这里
- 如何改进代码以生成安全的随机数
- 字符 * 和字符串在C++中有何不同?(在描述中编写代码)
- RBM尚未在代码上使用OpenACC进行改进
- C++代码改进,数组越界
- 如何改进此代码以便在多线程环境下运行
- 编译带有活动霓虹灯标志的代码几乎没有任何改进(甚至恶化)
- 如何改进我的代码以正确计算唯一行数
- 下面发布的图形代码的DFS遍历是否有任何改进
- Qt也不例外.这对C++代码有何影响
- 如何改进我的关于菌落生长的代码(c++)
- 帮助改进代码,提高时间效率