How is C++ std::vector implemented?

后端 未结 9 1348
不思量自难忘°
不思量自难忘° 2020-11-28 06:49

I have been using std::vector a lot, and recently I asked myself this question: \"How is std::vector implemented?\"

I had two alternatives:

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 07:41

    Section 23.2.4, ¶1 of the standard requires that arithmetic on pointers into a vector work the same as with pointers into an array.

    The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().

    This guarantees that the storage is in an array. Of course, if you resize the array to be bigger, it might get moved in memory.

提交回复
热议问题