Home > OS >  C vector of vector conversion
C vector of vector conversion

Time:02-10

I am fairly new to C and this might be a dumb question.

If I have 2 vectors,

vector<vector< double >> v1 , has values

and

const vector<vector< double> * > * v2, has no values

.

How would I go about storing the elements from v1 to v2 or would it be possible to cast v1 as

const vector<vector< double> * > *

CodePudding user response:

v1 is a vector of vectors, i.e. each element of v1 is a vector of type vector<double>.

v2 is a pointer to a vector of pointers, that is it points to a vector, which has pointers (to other vectors) as elements.

As you can see, v1 and v2 are completely different, in terms of types and binary layout, so no, you cannot cast one to another and have a valid program.

Assuming that with v2 you want to pass a list of pointers to v1, e.g. as a function argument, the way to do this is to construct a vector of pointers, where each element would be a pointer to the corresponding element of v1:

void foo(const vector<vector<double>*>* v2);

void bar(vector<vector<double>> const& v1)
{
    // Allocate a vector of pointers
    vector<vector<double>*> vp(v1.size(), nullptr);

    // Initialize the pointers to point to v1 elements
    for (std::size_t i = 0u, n = v1.size(); i < n;   i)
    {
        vp[i] = &v1[i];
    }

    // Pass the pointer to the vector of pointers to your destination
    foo(&vp);
}

It should be noted that this code is not cheap as it will have to allocate dynamic memory and initialize the vector of pointers. If your goal was to save performance on copying the data, you should pass a reference to the original vector instead (i.e. vector<vector<double>> const&).

  • Related