Are std::vector elements guaranteed to be contiguous?

前端 未结 7 2247
不知归路
不知归路 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:59

    The standard does in fact guarantee that a vector is continuous in memory and that &a[0] can be passed to a C function that expects an array.

    The exception to this rule is vector which only uses one bit per bool thus although it does have continuous memory it can't be used as a bool* (this is widely considered to be a false optimization and a mistake).

    BTW, why don't you use iterators? That's what they're for.

提交回复
热议问题