Are std::vector elements guaranteed to be contiguous?

前端 未结 7 2226
不知归路
不知归路 2020-11-22 03:41

My question is simple: are std::vector elements guaranteed to be contiguous? In order word, can I use the pointer to the first element of a std::vector as a C-array?

<
7条回答
  •  深忆病人
    2020-11-22 03:48

    This was missed from C++98 standard proper but later added as part of a TR. The forthcoming C++0x standard will of course contain this as a requirement.

    From n2798 (draft of C++0x):

    23.2.6 Class template vector [vector]

    1 A vector is a sequence container that supports random access iterators. In addition, it supports (amortized) constant time insert and erase operations at the end; insert and erase in the middle take linear time. Storage management is handled automatically, though hints can be given to improve efficiency. 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().

提交回复
热议问题