Dereference vector pointer to access element

前端 未结 2 1302
半阙折子戏
半阙折子戏 2020-12-12 15:07

If i have in C++ a pointer to a vector:

vector* vecPtr;

And i\'d like to access an element of the vector, then i can do this by

2条回答
  •  死守一世寂寞
    2020-12-12 15:32

    10000 ints will not be copied. Dereferencing is very cheap.

    To make it clear you can rewrite

    int a = (*vecPtr)[i];
    

    as

    vector& vecRef = *vecPtr; // vector is not copied here
    int a = vecRef[i];
    

    In addition, if you are afraid that the whole data stored in vector will be located on the stack and you use vector* instead of vector to avoid this: this is not the case. Actually only a fixed amount of memory is used on the stack (about 16-20 bytes depending on the implementation), independently of the number of elements stored in the vector. The vector itself allocates memory and stores elements on the heap.

提交回复
热议问题