sort函数请教!

xiaolai1012 2011-03-16 10:12:59
#include <iostream>
#include <algorithm>

using namespace std;

bool compare(int a,int b)
{
return a>=b; //这里为啥不能用>=或<=或==,一用就出错!!!
}
int main()
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for(i=0;i<20;i++)
cout<<a[i]<<endl;
sort(a,a+20,compare);
for(i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}

...全文
120 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
relive007 2011-03-16
  • 打赏
  • 举报
回复
不好意思,我说错了。
delphiwcdj 2011-03-16
  • 打赏
  • 举报
回复
当数组a里有相同的元素时,compare中不能有==
当数组a里没有相同的元素时,compare可以有==
delphiwcdj 2011-03-16
  • 打赏
  • 举报
回复

#include <iostream>
#include <algorithm>
using namespace std;
bool compare(int a,int b)
{
return (a>=b); // ok
}
int main()
{
int a[10]={2,4,1,23,5,76,0,43,24,65},i;
sort(a,a+10,compare);
for(i=0;i<10;i++)
cout<<a[i]<<endl;
return 0;
}

delphiwcdj 2011-03-16
  • 打赏
  • 举报
回复
The sort algorithm sorts the elements in the range [start,end) into ascending order. If two elements are equal, there is no guarantee what order they will be in.
relive007 2011-03-16
  • 打赏
  • 举报
回复
(a>b) || (a==b)

65,206

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧