Assume I have a C library API function which takes pointer of pointers as parameter. However since I am programming in C++ I would like to take advantage of std vector to deal with the dynamic memory. How can I efficiently convert vector of vector into pointer of pointer? Right now I am using this.
#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 achieve the goal? Can I get rid of the "new delete" thing by using iterator or some std method in this case? Thanks in advance.
Edit: According to answers I am now using this version to interface with C code. I am posting 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;
}
Looks more C++ like to me. Thanks for all!