[C++] 指针和自增自减操作符简洁的写法

数组复制:

// arr1 is an array of ints
int *source = arr1;
size_t sz = sizeof(arr1)/sizeof(*arr1); // number of elements
int *dest = new int[sz];                // uninitialized elements
while (source != arr1 + sz)
    *dest++ = *source++; //  copy element and increment pointers 

*dest++ = *source++ 等价于:

{
    *dest = *source; // copy element
    ++dest;  // increment the pointers
    ++source;
}

第2个例子:

vector<int>::iterator iter = ivec.begin();
// prints 10 9 8 ... 1
while (iter != ivec.end())
    cout << *iter++ << endl; // iterator postfix increment

同理  cout << *iter++ << endl; 等价于:

cout << *iter << endl;
++iter;

而  *++iter 则为 iter  先自增,然后将 iter 修改后的值用作 * 操作符的操作数。

简洁为美,code里要使用简洁表达式, 避免使用冗余表达式。

此外关于数组和指针的sizeof操作:

int arr[10];
int *p = arr;
cout << sizeof(arr) << endl; // 输出40
cout << sizeof(p) << endl; // 输出4

数组是数组,指针是指针,但是在绝大多数情况下,数组名会被转换为(衰变为)指针。上例中,arr是数组,p是指针,sizeof输出不同。因为sizeof返回整个数组的大小,可以用下面的方法得到元素的个数,假定ia为数组:

// sizeof(ia)/sizeof(*ia) returns the number of elements in ia
int sz = sizeof(ia)/sizeof(*ia);

下面的程序,本意是想执行 *x = *x + 1, 但实际不按设想输出:

#include <iostream>
#include <string>
using namespace std;

void doSomething(int *x, int *y)
{
    *x = *x++;
    *y = *y + 5;
}

int main()
{
    int x = 4;
    int y = 3;
    doSomething(&x, &y);
    cout << "x is now: " << x << endl; //outputs 4
    cout << "y is now: " << y << endl; //outputs 8
    return 0;
}

以下写法:

*x = *x+1;

等价于:

*x = ++*x;

等价于:

++*x;
所以, *x = *x++ 必须改为 *x = ++*x ++*x, 同理 --*x 也是类似的意思。


C++ Primer 5.5

Is array name a pointer?

C++ Incrementing a pointer

猜你喜欢

转载自blog.csdn.net/ftell/article/details/80102988