m.k
m.k

Reputation: 11

Passing a double pointer as argument to a function which expects a reference to a std::vector<double>

Is there any possible way to pass pointer to a double (double *) as argument to a function which expects a reference to a std::vector<double> argument in C++11

Upvotes: 1

Views: 197

Answers (2)

Caleth
Caleth

Reputation: 63152

Rather than copying the data into a vector, you could also change the function to take a span. You will still have to include the length along with the pointer.

e.g.

void takes_span(std::span<double>) {}

int main()
{
    std::vector<double> vec = { 1, 2, 3 };
    double arr[3] = { 4, 5, 6 };
    double * ptr = arr;

    takes_span(vec);
    takes_span(arr);
    takes_span({ptr, 3});
}

Upvotes: 1

Patrik
Patrik

Reputation: 2692

That will not be possible, you'll have to copy the data in a vector

vector<double> v(ptr, ptr + length);

Also, you cannot assign the data behind the pointer directly in the vector, copying is required, see here

Upvotes: 1

Related Questions