Frage

Is it safe to get address of first element in std::vector and use it like raw array? Is data aligned continously? What c++ standard says (c++98 vs c++11)? Is it a common practice by the way?

I have some array which size may vary and function which takes pointer and number of elements as argument. It would be great to manage data with std::vector and use it with my_func at same time.

std::vector<int> my_vector;
void my_func(int* int_ptr, int num_ints);
// ..
my_func(&my_vector[0], my_vector.size());
War es hilfreich?

Lösung

C++11 (and C++03 for that matter) guarantees that the data in std::vector are contiguous. This means, that in your case, &my_vector[0] can be thought of as the pointer to the zeroth element of that array and normal pointer arithmetic can be used to access the other elements. It's preferred to use my_vector.data() to recover the pointer to the zeroth element.

C++98 almost guarantees it.

Note that it's not true for std::vector<bool> for any of the C++ standards. This is because std::vector<bool> is implemented as a particular specialisation.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top