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, a vector will probably use an array internally so I see why this works, I’m just wondering whether or not this is defined behavior (like, is an implementor allowed to run an implementation of std::vector with which this would break).
If there are conflicts between the standards, I’m interested in what the C++11 standard says.
Yes it is allowed, if the
std::vectoris not empty. If thevectoris empty,vec[0]will evoke Undefined Behavior.std::vectoris required to store elements contiguously.There is also
data() method, but it is C++11 only.Important:
This will not work on
std::vector<bool>(bit-efficient specialization). But it is also not a container, and IMO it should be deprecated.