How is C++ std::vector implemented?

后端 未结 9 1289
不思量自难忘°
不思量自难忘° 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.

    0 讨论(0)
  • 2020-11-28 07:43

    They use a dynamically allocated array that is regrown as needed. It is necessary to use something like an array so that the elements are contiguous in memory which is guaranteed by the standard.

    Incidentally, one common way of regrowing an array is to double the size as needed. This is so that if you are inserting n items at most only O(log n) regrowths are performed and at most O(n) space is wasted.

    You can read one implementation for yourself at SGI (where STL was originally conceived).

    0 讨论(0)
  • 2020-11-28 07:47

    I believe the STL uses option #2 (or something similar) because a std::vector<> is guaranteed to store the elements in contiguous memory.

    If you're looking for a memory structure that doesn't need to use contiguous memory, look at std::deque.

    0 讨论(0)
提交回复
热议问题