Does insertion of elements in a vector damages a pointer to the vector?

后端 未结 6 596
心在旅途
心在旅途 2021-01-13 10:19

In a program to simulate logic gates I switched from using arrays

node N[1000];

to vectors

vector N;
<         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 10:42

    Yes, inserts will invalidate old pointers to vector elements on reallocation. If you want to use stable pointers really hard, you can switch from vector to deque. It offers a very similar interface to vector and can grow without reallocating and moves previous contents by allocating further chunks.

    The price you pay for using a deque instead of a vector is one more level of indirection on random access. Depending on your usage, that may be totally irrelevant. You should iterate over deque the whole deque if necessary by using iterators. That will be as fast a iterating over a vector.

    The gain is: zero reallocations!

提交回复
热议问题