[Learning log] 2022.11.10 C++11 constant expressions, user-defined literals, native string literals, class improvements, Leetcode Pain Xun preferred 50 mentions T1

constant expression

The main purpose of constant expressions is to allow some calculations to occur at compile time, that is, when the code is compiled rather than run.

This is a big optimization: if something can be done at compile time, it will be done only once, instead of being calculated every time the program runs.

Using constexpr, you can create a compile-time function:

constexpr int GetConst()
{
    return 3;
}

int main()
{
    int arr[ GetConst() ] = {0};
    enum { e1 = GetConst(), e2 };

    constexpr int num = GetConst();

    return 0;
}

Restrictions on constexpr functions:

  1. There can be only one return statement in a function (with very few exceptions)
  2. The function must return a value (cannot be a void function)
  3. Must have been defined before using
  4. return function and global data that cannot use non-constant expressions in the return statement expression, and must be a constant expression
//err,函数中只能有一个return语句
constexpr int data()
{
    constexpr int i = 1;
    return i;
}

constexpr int data2()
{
    //一个constexpr函数,只允许包含一行可执行代码
    //但允许包含typedef、 using 指令、静态断言等。
    static_assert(1, "fail");
    return 100;
}

int a = 3;
constexpr int data3()
{
    return a;//err, return返回语句表达式中不能使用非常量表达式的函数、全局数据
}

int main()
{
    constexpr int func(); //函数声明,定义放在main函数后面
    constexpr int c = func();  //err, 无法通过编译, 在使用前必须已有定义

    return 0;
}

constexpr int func()
{
    return 1;
}

Constructors for constant expressions have the following restrictions:

  1. function body must be empty
  2. Initializer lists can only be assigned by constant expressions
struct Date
{
    constexpr Date(int y, int m, int d): year(y), month(m), day(d) {}

    constexpr int GetYear() { return year; }
    constexpr int GetMonth() { return month; }
    constexpr int GetDay() { return day; }

private:
    int year;
    int month;
    int day;
};

int main()
{
    constexpr Date PRCfound {1949, 10, 1};
    constexpr int foundmonth = PRCfound.GetMonth();

    cout << foundmonth << endl;  // 10

    return 0;
}

user-defined literal

User-defined literal values, or "custom suffixes" are more intuitive, and their main function is to simplify the reading and writing of codes.

long double operator"" _mm(long double x) { return x / 1000; }
long double operator"" _m(long double x)  { return x; }
long double operator"" _km(long double x) { return x * 1000; }

int main()
{
    cout << 1.0_mm << endl; //0.001
    cout << 1.0_m  << endl; //1
    cout << 1.0_km << endl; //1000

    return 0;
}

According to the C++11 standard, only the following parameter lists are legal:

char const *
unsigned long long
long double
char const *, size_t
wchar_t const *, size_t
char16_t const *, size_t
char32_t const *, size_t

size_t operator"" _len(char const * str, size_t size)
{
    return size;
}

int main()
{
    cout << "mike"_len <<endl; //结果为4

    return 0;
}

char const * operator"" _r(char const* str)
{
    return str;
}

int main()
{
    cout << 250_r <<endl; //结果为250

    return 0;
}

raw string literals

Raw string literals enable users to write strings "what you see is what you get". The declaration of a native string in C++11 is quite simple. You only need to add a prefix, the letter R, to the string, and use parentheses to mark it in quotation marks, and you can declare the string literal as a native string.

int main()
{
    cout << R"(hello,\n
         world)" << endl;

    return 0;
}

class improvements

inheritance construct

C++11 allows derived classes to inherit the constructors of the base class (except default constructor, copy constructor, move constructor).

class A
{
public:
    A(int i) { cout << "i = " << i << endl; }
    A(double d, int i) {}
    A(float f, int i, const char* c) {}
    // ...
};

class B : public A
{
public:
    using A::A; // 继承构造函数
    // ...
    virtual void ExtraInterface(){}
};

delegate constructor

Similar to the inherited constructor, the delegated constructor is also an improvement of the C++ constructor in C++11, and its purpose is also to reduce the time for programmers to write constructors.

If a class contains multiple constructors, C++11 allows the use of a constructor in a definition within another constructor, but this must be done through an initialization list , as follows:

class Info
{
public:
    Info() : Info(1) { }    // 委托构造函数
    Info(int i) : Info(i, 'a') { } // 既是目标构造函数,也是委托构造函数
    Info(char e): Info(1, e) { }

private:
    Info(int i, char e): type(i), name(e) { /* 其它初始化 */ } // 目标构造函数
    int  type;
    char name;
    // ...
};

Inheritance control: final and override

class B1 final {}; // 此类不能被继承
//class D1: public B1 {}; // error!

class B
{
public:
//  virtual void func() override // error! 指定了重写但实际并没重写,没有基类
//  {
//      cout << __func__ << std::endl;
//  }
    virtual void f() const
    {
        cout << __func__ << std::endl;
    }
    virtual void fun()
    {
        cout << __func__ << std::endl;
    }
};

class D : public B
{
public:
    virtual void f(int)      // ok! 隐藏,由于没有重写同名函数B::f,在D中变为不可见
    {
        cout << "hiding: " <<__func__ << std::endl;
    }
//  virtual void f() override   // error! 指定了重写但实际并没重写,类型声明不完全相同
//  {
//      cout << __func__ << std::endl;
//  }
    virtual void fun() override final // ok! 指定了重写实际上也重写了,同时,指定为最终,后代类中不能再重写此虚函数
    {
        cout << __func__ << std::endl;
    }
};

class D2 : public D
{
public:
    virtual void f() const      // ok! 重写B::f(),同时,由于没有重写D::f(int),在D2中变不可见
    {
        cout << __func__ << std::endl;
    }
//  virtual void fun() // error! 基类的此虚函数被指定为最终,不能被重写,虽然没有显示指定"override"
//  {
//      cout << __func__ << std::endl;
//  }
//  virtual void fun() override // error! 基类的此虚函数被指定为最终,不能被重写
//  {
//      cout << __func__ << std::endl;
//  }
};

Leetcode Pain Xun Optimal 50 mention T1

Adding two numbers in ListNode

ListNode_Code Blind Evolution Blog-CSDN Blog_listnode code] ListNode. https://blog.csdn.net/qq_38494269/article/details/126004648?ops_request_misc=&request_id=&biz_id=102&utm_term=listnode&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-462.14^ v63^control_1, 201^v3^add_ask, 213^v2^t3_control1 Linked lists I know (below)_Shangshan Catch Fish Blog-CSDN Blog Deletion and insertion operations of double linked lists, insertion and deletion of circular linked lists. Reverse and merge operations of singly linked list. https://blog.csdn.net/FisherandPiger/article/details/126236579?ops_request_misc=&request_id=&biz_id=102&utm_term=%20temp%20=%20cur%20-%3E%20next;%20%20%20%20% 20%20%20%20%20%20&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduweb~default-0-126236579.142^v63^control_1,201^v3^add_ask,213^v2^t3_control1 list Related (design linked list and ring linked list problem)_weixin_46213145's blog-CSDN blog_while(cur->next)The design of the two-way linked list includes deleting and adding nodes, etc., such as flipping the linked list, etc. %2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=166808415016800186581900&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-1-125899898-null-null.142^ v63^control_1,201^v3^add_ask,213^v2^t3_control1&utm_term=%20temp%20%3D%20cur%20-%3E%20next%3B%20%20%20%20%20%20%20%20% 20%20%20%20%20cur-%3Enext%20%3D%20pre%3B list (ListNode)_hurricane&&storming's blog-CSDN blog_listnodeListNode list node ADT supported operation interface operation interface function data () the data object stored in the current node pred () the position of the predecessor node of the current node succ () the position of the successor node of the current node insertAsPred (e) insert the predecessor node and store it in the referenced object e, returns the position of the new node insertAsSucc(e) inserts the successor node and saves it in the referenced object e, returns the position list of the new node Operation interface supported by ADT Operation interface function applicable object size() returns the list of the total number of nodes first(), la https ://blog.csdn.net/weixin_48033173/article/details/113035785?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166808175016782412568745%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id= 166808175016782412568745&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-2-113035785-null-null.142^v63^control_1,201^v3^add_ask,233^_control1^m&

cpp

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *head = nullptr, *tail = nullptr;
        int carry = 0;
        while (l1 || l2) {
            int n1 = l1 ? l1->val: 0;
            int n2 = l2 ? l2->val: 0;
            int sum = n1 + n2 + carry;
            if (!head) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail->next = new ListNode(sum % 10);
                tail = tail->next;
            }
            carry = sum / 10;
            if (l1) {
                l1 = l1->next;
            }
            if (l2) {
                l2 = l2->next;
            }
        }
        if (carry > 0) {
            tail->next = new ListNode(carry);
        }
        return head;
    }
};

c#

public class Solution {
    public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            int sum = n1 + n2 + carry;
            if (head == null) {
                head = tail = new ListNode(sum % 10);
            } else {
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            carry = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry > 0) {
            tail.next = new ListNode(carry);
        }
        return head;
    }
}

Guess you like

Origin blog.csdn.net/Angelloveyatou/article/details/127787727