Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass std::vector as const float *? [duplicate]

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.

like image 329
Darkgaze Avatar asked Jan 03 '23 22:01

Darkgaze


2 Answers

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].

like image 123
songyuanyao Avatar answered Jan 20 '23 04:01

songyuanyao


function(myVector.data(), myVector.size());
like image 37
iehrlich Avatar answered Jan 20 '23 05:01

iehrlich