今天做了个小测试,发现sort函数第三个参数不应该添加,添加之后反而效率更低了.
比如说,一般情况下,要将N个数升序排列,sort(arr,arr+arr.length(),cmp) 这个cmp函数是这样的:
bool cmp(int a,int b)
{
return a>b;
}
这样就可以使序列升序,但是效率没有sort(arr,arr+arr.length());reverse(arr,arr+arr.length());效率高.
Test Code:
#include<iostream>
#include<algorithm>
#include<windows.h>
#include<ctime>
#define N 100000
using namespace std;
LARGE_INTEGER t1,t2,tc;
void begin()
{
QueryPerformanceFrequency(&tc);
QueryPerformanceCounter(&t1);
}
void end()
{
QueryPerformanceCounter(&t2);
cout<<1.0*(t2.QuadPart-t1.QuadPart)/tc.QuadPart<<endl;
}
inline bool cmp(int a,int b)
{
return a>b;
}
int main()
{
srand(time(0));
int i,arr[N],arr1[N];
for(i=0;i<N;i++)
{
arr[i]=rand()%999+1;
arr1[i]=arr[i];
}
begin();
sort(arr,arr+N);
reverse(arr,arr+N);
end();
begin();
sort(arr1,arr1+N,cmp);
end();
return 0;
}
Test result:
0.0585591
0.106811
请按任意键继续. . .