4

My function is:

void function(const float *, int sizeOfArray){...}

My vector is:

std::vector<float> myVector(size, val);

I read in the docs you can use myVector[0] as standard c++ static arrays operations.

How can I pass that vector to that function without having to copy the values to a new dynamic array? (I want to avoid using new / delete just for this).

Is it something like...?

function(myVector[0], size);

I'm using C++11 by the way.

Darkgaze
  • 2,280
  • 6
  • 36
  • 59

2 Answers2

9

You can use std::vector::data (since C++11) to get the pointer to the underlying array.

Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty (data() is not dereferenceable in that case).

e.g.

function(myVector.data(), myVector.size());

Is it something like...?

function(myVector[0], size);

myVector[0] will return the element (i.e. float&), not the address (i.e. float*). Before C++11 you can pass &myVector[0].

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • `&myVector[0]` can be used in all versions of C++, not just before C++11. `myVector.data()` can also be used in C++11 and later. – Peter Jun 02 '17 at 11:20
1
function(myVector.data(), myVector.size());
iehrlich
  • 3,572
  • 4
  • 34
  • 43