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!
c ++ pointers c ++ 11 stdvector
yc2986
source share