klm123
klm123

Reputation: 12865

Pointer to all std::vector elements

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.

Upvotes: 1

Views: 120

Answers (4)

kinsung
kinsung

Reputation: 3

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

Upvotes: 0

Raxvan
Raxvan

Reputation: 6505

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.

Upvotes: 0

rubenvb
rubenvb

Reputation: 76529

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.

Upvotes: 2

David
David

Reputation: 28178

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

Upvotes: 7

Related Questions