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
/* C like api */
void foo(short **psPtr, const int x, const int y);
int main()
{
const int x = 2, y = 3;
std::vector> vvsVec(x, std::vector(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
/* C like api */
void foo(short **psPtr, const int x, const int y);
int main()
{
const int x = 2, y = 3;
std::vector> vvsVec(x, std::vector(y, 0));
std::vector 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!
Answer
Is this the best way to achieve the goal?
If you are sure that the vector of vectors will outlive psPtr
, then yes. Otherwise, you run the risk that psPtr
will contain invalid pointers.
Can I get rid of the "new delete" thing by using iterator or some std method in this case?
Yes. I suggest using:
std::vector psPtr(vvsVec.size());
and then use &psPtr[0]
in the call to the C API function. That removes the burden of memory management from your code.
foo(&psPtr[0]);
No comments:
Post a Comment