Is & vec [0] defined behavior for std :: vector vec?

I see this a lot:

std::vector<Something> vec; do_something_with_vec(vec); Something *arr=&vec[0]; do_something_that_needs_carray(arr); 

I mean, the vector will probably use the array internally, so I understand why this works, I'm just wondering if this behavior is defined (for example, the developer is allowed to run the std :: vector implementation with which it will break).

If there are contradictions between the standards, I'm interested in what the C ++ 11 standard says.

+8
c ++ c ++ 11
source share
3 answers

Yes, this is allowed if std::vector not empty. If vector empty, vec[0] will call Undefined Behavior.

std::vector is required to store elements contiguously.

There is also a data( ) method, but it is only C ++ 11.

Important:

This will not work on std::vector<bool> (bit-efficient specialization). But it is also not a container, but IMO it should be deprecated.

+17
source share

It's fine. But if vec empty, this behavior is undefined. Better to use vec.data() , which will also work if vec empty.

+9
source share

Yes, that’s fine, because the items are guaranteed to be stored adjacent to each other. The standard confirms this:

Elements of a vector are stored adjacent, which means that if v is vector<T, Allocator> , where T is some type other than bool , then it obeys the identifier &v[n] == &v[0] + n for all 0 <= n < v.size() .

+6
source share

All Articles