Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Work with a std::vector that matches the memory of an array of double

Tags:

c++

c

vector

I am trying to connect two existing codebases — one in C, the other in C++. The C++ code uses std::vector whereas the other one is based on arrays of double. I would like to pass arrays of double from the C code, perform operations on std::vectors in the C++ code, and eventually have these operations reflected in the arrays of double.

Is it possible to create a std::vector that matches the memory occupied by the array of double?

I have tried several options, but they all involve the creation of a new vector and a copy of the array of double into that vector. For instance:

void fcn(double* a, int sizeofa)
{
    std::vector<double> vect_a;
    vect_a.assign(a, a + sizeofa);

    // operations on vect_a

    for (int i=0;i<sizeofa;i++) { a[i] = vect_a[i]; }
}
like image 853
vspsonn Avatar asked Mar 11 '23 21:03

vspsonn


2 Answers

As noted in the comments, std::vector manages its own memory, you can't make it use some other memory as the backing store (it would have no idea what to do if the size changed, among other issues).

But you may not need a vector at all; if you're just using vector for non-dynamic size related features, it's highly likely you could just use the functions from <algorithm> to perform the same work directly on the array that you wanted to use vector's methods to accomplish.

like image 173
ShadowRanger Avatar answered Mar 19 '23 12:03

ShadowRanger


In C++, functions requiring a container often denote the container by Iterator pairs, which are templated. This is very convenient, especially when interfacing with external libraries, because an iterator isn't a type. It is a concept, which is just an interface that defines what a type should look like. Turns out, C style pointers are valid iterators. This means that you can use any C++ function that accepts an iterator with any C array.

So, now to answering your question. In other answers, it was made clear that you cannot make a std::vector control the memory allocated by a C array because a std::vector requires full ownership over the data because it wouldn't know how to deallocate it. You can copy the C array into a vector, but there is no point in using a std::vector unless you want it's resizing capabilities.

In summary: try not to pass std::vectors into functions because iterators are more generic. If you must avoid templates (virtual function, etc) than use a C style array because those are very flexible too, you can turn a std::vector into a C array, but the other way requires a copy.

I know this is hard if you have already made your code interface with std::vectors, in which case a copy is the only possible way. Prefer C style arrays when you don't need to resize the array, and maybe in the future std::array_view

like image 44
Russell Greene Avatar answered Mar 19 '23 12:03

Russell Greene