1. 程式人生 > >【程式設計技巧與C++11特性】總結

【程式設計技巧與C++11特性】總結

一,程式設計技巧

1.1排序效能問題

C ++的排序函式有兩種用法:

  1. 傳入一個functor物件;
  2. 直接傳入一個排序函式。
#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)。

 相關知識:

排隊

  1.  使用內聯的,目的是為了提高函式的執行效率,“用函式內聯取代巨集”(注意是定義而非宣告)。

  2. 很明顯,類的行內函數也是一個真正的函式編譯器在呼叫一個行內函數時,會首先檢查它的引數的型別,保證呼叫正確。然後進行一系列的相關檢查,就像對待任何一個真正的函式一樣。這樣就消除了它的隱患和侷限性

  3. inline可以作為某個

    類的成員函式,當然就可以在其中使用所在類的保護成員及私有成員。

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()){}

#暫時先發布著,日後再修改