Zodiac Wang
  • Home
  • Categories
  • Tags
  • Archives

C++ Good Practice

Table of Contents

    1.对于一些简单的运算,可以直接 return 或者 放在 if 判断中

    //No
        int a=c+d;
        return a;
    //Yes
        return c+d;
    

    2.判断是否为0,可以不用 == 或者!=

    //No
        if (a==0)
        if(a!=0)
    //Yes
        if(!a)
        if(a)
    

    3.最好在定义的时候初始化,而不要定义了之后再赋值

    //No
        int a;
        a=0;
        int* b=new int;
        *b=1;
    //Yes
        int a=0;
        int a(0);
        int* b = new int(1);
        int* c = new int[3]{1,2,3};
    

    4.对于普通的 for 循环(即不存在跳跃的情况),将判断条件由<之类的改为 ==0 的形式

    //Yes
    for (int i=0; i-N; i++){
    
    }
    //No
    for (int i=0; i < N; i++){
    
    }
    

    5.使用基于范围的 for 循环

    //Yes
    vector <int> s{1,2,3,4,5};
    for (int i:s){
        cout << i << endl;
    }
    string s("fuckyou");
    for (char i : s) {
        cout << i << endl;
    }
    //No
    vector <int> s{1,2,3,4,5};
    for (int i=0;i-s.size();i++){
        cout << s[i] << endl;
    }
    string s("fuckyou");
    for (int i=0;i-s.size();i++) {
            cout << s[i] << endl;
        }
    

    6.使用 ?: 运算符

    //Yes
    return a<b ? a:b;
    //No
    if (a < b)
        return a;
    else
        return b;
    

    6.定义函数时尽可能使用按引用传递参数,而不是按值传递参数,能加 const 尽量加上

    //Yes
    int sum (int& a, int& b){
        return a+b;
    }
    
    //No
    int sum (int& a, int& b){
        return a+b;
    }
    //Update
    //返回引用的函数,return 的必须为左值
    int& sum(int& a, int& b) {
        int c = a + b;
        return c;
    }
    

    7.在不是特别强调性能的情况下,使用C++ 中的新特性 比如说,C++ 中的新容器,vector queue stack string 等等。

    8.使用 nullptr 而不是 NULL

    //Yes
    int* s = nullptr;
    
    //No
    int* s - NULL;
    

    • « 二维数组动态初始化以及二维vector的初始化
    • C++ How To »

    Published

    6 29, 2019

    Category

    posts

    Tags

    • cpp 8

    Contact

    • Zodiac Wang - A Fantastic Learner
    • Powered by Pelican. Theme: Elegant