Convert a vector vector to a pointer pointer

Suppose I have a C library API function that takes a pointer to pointers as a parameter. However, since I program in C ++, I would like to use a std vector to work with dynamic memory. How can I efficiently convert a vector of a vector to a pointer pointer? I am using it now.

#include <vector> /* C like api */ void foo(short **psPtr, const int x, const int y); int main() { const int x = 2, y = 3; std::vector<std::vector<short>> vvsVec(x, std::vector<short>(y, 0)); short **psPtr = new short*[x]; /* point psPtr to the vector */ int c = 0; for (auto &vsVec : vvsVec) psPtr[c++] = &vsVec[0]; /* api call */ foo(psPtr, x, y); delete[] psPtr; return 0; } 

Is this the best way to reach your goal? Can I get rid of the β€œnew delete” thing with an iterator or some std method in this case? Thanks in advance.

Edit: According to the answers, I now use this version to interact with C code. I post it here.

 #include <vector> /* C like api */ void foo(short **psPtr, const int x, const int y); int main() { const int x = 2, y = 3; std::vector<std::vector<short>> vvsVec(x, std::vector<short>(y, 0)); std::vector<short*> vpsPtr(x, nullptr); /* point vpsPtr to the vector */ int c = 0; for (auto &vsVec : vvsVec) vpsPtr[c++] = vsVec.data(); /* api call */ foo(vpsPtr.data(), x, y); return 0; } 

C ++ looks more like me. Thanks everyone!

+7
c ++ pointers c ++ 11 stdvector
source share
2 answers

Is this the best way to reach your goal?

If you are sure that the vector of vectors will survive psPtr , then yes. Otherwise, you risk psPtr containing invalid pointers.

Is it possible to get rid of the β€œnew delete” using an iterator or some std method in this case?

Yes. I suggest using:

 std::vector<short*> psPtr(vvsVec.size()); 

and then use &psPtr[0] in the C API function call. This removes the memory management burden from your code.

 foo(&psPtr[0]); 
+4
source share
 std::vector<short*> vecOfPtrs; for (auto&& vec : vvsVec) vecOfPtrs.push_back(&vec[0]); foo(&vecOfPtrs[0]); 
+3
source share

All Articles