Pregunta

What is the optimal (from code readability and semantics) way to get a pointer to all std::vector elements so it can be used as usual array? I used to use:

void Func( int* )

  ...

std::vector<int> x(1000);
Func(&(x[0]));

but i wonder is there any prettier way to do this? x.begin() returns vector::iterator.

¿Fue útil?

Solución

x.data() in C++11 or &x.front() in C++03

Otros consejos

Aside from Dave's answers, you can leave out the parentheses:

int * xP = &x[0];

Which is really as short as it's going to get.

You can also write it this way: int * xp = &x.front(), but there is no optimal solution for this , everything you write should be optimized into the same result by the compiler.

A vector is guaranteed to have contigious storage in C++11, and also in platforms from vc++6.0 to vc++ 2012.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top