C++primer第四版第四章数组与指针

来源:互联网 发布:贪心算法 最优合并 编辑:程序博客网 时间:2024/05/19 16:38

Talk is cheap, show me the code.

  1. 现代C++尽量不是用指针和数组,而是使用迭代器和string,vector。

  2. 数组是不能改变长度的,两个数组不能直接赋值来实现复制,两个数组不能直接比较大小,必须通过比较每个数组元素来比较大小。vector可以改变长度,两个vector也可以通过直接赋值来实现复制,两个vector可以通过直接使用关系运算符来比较大小。

    vector<int> vect = {1, 2, 3} //right
    vector<int> vect1(1,2,3);  //wrong

  3. 指向const常量的指针和指向变量的const指针:

    int a = 1;
    const int b =2;
    const int *p1 = &b; //right p1的值可以改变,不能通过*p1改变b的值
    const int *p2 = &a; //right 但是不能通过*p2修改a的值,p2的值可以改变
    int *const p3 = &a; //right 指向a的const指针,p3的值不能改变,但是可以通过*p3改变a的值
    const int *const p4 = &b; //right 不能修改p4的值,也不能通过*p4修改b的值

    typedef string *pstring;
    string s = "hel";
    const pstring p = &s; //等同于 string *const p = &s是指向s的const指针,而不是指向const的指针

  4. string转换成数组可以使用c_str()函数。

    string str = "hello";
    const char *str1 = str.c_str();

  5. 数组转换成vector可以使用vector的构造函数。

    int arr[5] = {1, 2, 3, 4, 5};
    int *parr = a;
    arrlen = 5;
    vector<int> vect(parr, parr + arrlen);(拷贝整个数组)

  6. 指针数组和数组指针:

    `int *p[4] //指针数组,每个元素都是一个指针
    int (*p)[4] //数组指针,这是一个指针,指向一个包含4个元素的数组

0 0
原创粉丝点击