大神来给我讲一讲algorithm里面的sort函数(带有一个判断函数的)

a291936324 2011-04-18 10:38:41
我下面的compare只要里面的比较不是<个,基本就错了,<=不行。>也不行,这是为什么呢?求知道,要深入源码里面的更好。
bool compare(str str1, str str2)
{
return str1.i < str2.i ;
}

sort(str1.begin(), str1.end(), compare);
...全文
150 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
shaotine_wu 2011-04-18
  • 打赏
  • 举报
回复
代码应该没问题,请确定str结构类型中是否含有其他比较符的重载
a291936324 2011-04-18
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 kingstarer 的回复:]
<=肯定是不行的

当str1.i = str2.i时,str1.i <= str2.i为真
!(str2.i < str1.i)为假
[/Quote]这是为什么呢?为什么要等价于!(str2.i > str1.i)?
我的i是int型的。

struct str
{
public:
std::string st;
int i;
public:
str( std::string st1, int i1): st( st1), i( i1)
{}
};
kingstarer 2011-04-18
  • 打赏
  • 举报
回复
<=肯定是不行的

当str1.i = str2.i时,str1.i <= str2.i为真
!(str2.i < str1.i)为假
kingstarer 2011-04-18
  • 打赏
  • 举报
回复
你的i是什么类型的

你必须保证 str1.i > str2.i

等价于 !(str2.i > str1.i)
luciferisnotsatan 2011-04-18
  • 打赏
  • 举报
回复
bool UDgreater ( int elem1, int elem2 )
{
return elem1 > elem2;
}

luciferisnotsatan 2011-04-18
  • 打赏
  • 举报
回复
什么意思?你的代码没问题呀。你要改成 >,那排序就是从大到小了

template<class RandomAccessIterator, class Pr>
void sort(
RandomAccessIterator _First,
RandomAccessIterator _Last,
BinaryPredicate _Comp
);

_Comp
User-defined predicate function object that defines the comparison criterion to be satisfied by successive elements in the ordering. A binary predicate takes two arguments and returns true when satisfied and false when not satisfied


lanzhengpeng2 2011-04-18
  • 打赏
  • 举报
回复
只要一个小于就能判断其他所有情况了。
A>B -> B<A
A<=B -> !(B<A)
A>=B -> !(A<B)
A==B -> !(A<B) && !(B<A)
A!=B -> A<B || B<A

64,647

社区成员

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

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