关于sort的cmp写法

版权声明:本文为博主原创文章,未经博主允许必须转载。 https://blog.csdn.net/qq_35950004/article/details/88941067

有一些cmp写法会使得sort卡死。
经过实验,发现需要不存在有两个元素 u , v u,v 使得 c m p ( u , v ) = 1 , c m p ( v , u ) = 1 cmp(u,v) = 1 , cmp(v,u) = 1 ,否则就有可能在大数据下卡死。(当然显然不能排序的也会卡死)
注意是可以 c m p ( u , v ) = 0 , c m p ( v , u ) = 0 cmp(u,v)=0,cmp(v,u)=0 的。
所以如果需要排序的元素中有相等的,那么返回0.。。。。。

测试代码:

#include<bits/stdc++.h>
using namespace std;

bool cmp(const int &u,const int &v){ return u<=v; }// TLE

int a[1000000];

struct cmp2{
	bool operator ()(const int &u,const int &v){ return u<v;  }
};
multiset<int,cmp2>st;

int main(){
	for(int i=0;i<100000;i++) a[i] = rand() % 2;
	sort(a,a+100000,cmp);
	printf("%d\n",a[0]);
	
	for(int i=0;i<100000;i++) st.insert(a[i]);
	printf("%d\n",a[0]);
}

猜你喜欢

转载自blog.csdn.net/qq_35950004/article/details/88941067
今日推荐