Home > database >  How to convert vector<vector<int>>to int**?
How to convert vector<vector<int>>to int**?

Time:11-16

vectoris easy to obtain int* through vector::data(), so how to convert vector<vector>to int**?

int main(int argc, char *argv[])
{
    std::vector<std::vector<int>> temp {{1,2,3},{4,5,6}};
    int **t;
     t = reinterpret_cast<int **>(std::data(temp));
     for (int i = 0; i < 2;   i)
     {
         for (int j = 0; j < 3;   j)
         {
             std::cout << t[i][j] << "    ";
         }
     }
}
// out : 1    2    3    0    0    0

It's obviously wrong.

CodePudding user response:

There is a simple "trick" to create the pointer that you need, as a temporary workaround while the code is being refactored to handle standard containers (which is what I really recommend that you should do).

The vectors data function returns a pointer to its first element. So if we have a std::vector<int> object, then its data function will return an int*. That puts us about halfway to the final solution.

The second half comes by having a std::vector<int*>, and using its data function to return an int**.

Putting this together, we create a std::vector<int*> with the same size as the original std::vector<...> object, and then initialize all elements to point to the sub-vectors:

std::vector<std::vector<int>> temp;

// ...

// Create the vector of pointers
std::vector<int*> pointer_vector(temp.size());

// Copy the pointers from the sub-vectors
for (size_t i = 0; i < temp.size();   i)
{
    pointer_vector[i] = temp[i].data();
}

After the above loop, then you can use pointer_vector.data() to get the int** pointer you need.


Until you have refactored the code, you could put this in an overloaded function that does the conversion and calls the actual function:

// The original function
void some_function(int**);

// Creates a vector of pointers, and use it for the
// call of `some_function(int**)`
void some_function(std::vector<std::vector<int>> const& actual_vector);
  •  Tags:  
  • c
  • Related