Sunday, May 26, 2019

c++ - Convert vector of vector to pointer of pointer



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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...