【程式設計技巧與C++11特性】總結
阿新 • • 發佈:2018-11-28
一,程式設計技巧
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()){}
#暫時先發布著,日後再修改