mercredi 22 février 2017

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 <vector>

/* C like api */
void foo(short **psPtr);    

int main()
{
    const int x = 2, y = 3;
    std::vector<std::vector<short>> vvsVec(2, 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);        

    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.

Aucun commentaire:

Enregistrer un commentaire