【编程技巧与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()){}

#暂时先发布着,日后再修改

猜你喜欢

转载自blog.csdn.net/qwe641259875/article/details/83153200
今日推荐