一,编程技巧
1.1排序性能问题
C ++的排序函数有两种用法:
- 传入一个functor对象;
- 直接传入一个排序函数。
#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;
#define rep(i,a,b) for(int i =(a);i<b;++i)
const int N = 10000000;
struct TS{
int a,b,c;
};
//Question 1: what is inline?
inline bool cmp(const TS& t1, const TS& t2) { //排序函数
if (t1.a != t2.a) return t1.a < t2.a;
if (t1.b != t2.b) return t1.b < t2.b;
return t1.c <= t2.c;
}
int cmp4qsort(const void *a, const void *b){
TS *t1 = (TS*)a, *t2 = (TS*)b;
if(t1->a != t2->a) return t1->a - t2->a;
if(t1->b != t2->b) return t1->b - t2->b;
return t1->c - t2->c;
}
struct cmpFunctor{ //functor对象
inline bool operator()(const TS& t1, const TS& t2){
if (t1.a != t2.a) return t1.a < t2.a;
if (t1.b != t2.b) return t1.b < t2.b;
return t1.c <= t2.c;
}
};
TS tss[N];
void genData(){
rep(i,0,N){
tss[i].a = rand();
tss[i].b = rand();
tss[i].c = rand();
}
}
int main()
{
srand(time(NULL));
genData();
clock_t start = clock();
sort(tss,tss+N,cmp); //直接传入排序函数
printf("sort by function pointer:%ld\n", clock()-start);
genData();
start = clock();
sort(tss,tss+N,cmpFunctor()); //传入functor对象
printf("sort by functor:%ld\n", clock()-start);
genData();
start = clock();
qsort(tss, N, sizeof(TS), cmp4qsort);
printf("qsort by function pointer:%ld\n", clock()-start);
return 0;
}
根据结果,我们可以发现传入functor比直接使用函数更快,在我的环境中并没有很明显(mingw)(然而在作者的环境中,排序由functor是最快的,g ++ 4.8.0)。
相关知识:
排队
inline int max(int a, int b)
{
return a > b ? a : b;
}
//则调用:
cout<<max(a, b)<<endl;
//在编译时展开为:
cout<<(a > b ? a : b)<<endl;
1.1.2整数输入
int redint(){
int x; scanf("%d",&x); return x; //此处scanf也可以根据需要换成cin>>x
}
vector<int> vc;
vc.push_back(readint());
1.1.3循环宏定义
用clion的话因为有自动补全,并没有感受到敲代码效率有多大的提升,但是如果使用比较原始的编译器的话,效率会大大提升。
#define _for(i,a,b) for(int i = (a); i<(b); ++i)
#define _rep(i,a,b) for(int i = (a); i<=(b); ++i)
//使用方法
vector b;
_for(i,1,a.size()){}
#暂时先发布着,日后再修改