将矢量矢量转换为指针指针

yc2*_*986 8 c++ pointers stdvector c++11

假设我有一个C库API函数,它将指针指针作为参数.但是由于我使用C++编程,我想利用std向量来处理动态内存.如何有效地将矢量矢量转换为指针指针?现在我正在使用它.

#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;
}
Run Code Online (Sandbox Code Playgroud)

这是实现目标的最佳方式吗?在这种情况下,我可以通过使用迭代器或某些std方法来摆脱"新删除"的事情吗?提前致谢.

编辑: 根据答案我现在使用此版本与C代码接口.我在这里发帖.

#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;
}
Run Code Online (Sandbox Code Playgroud)

看起来更喜欢我的C++.谢谢大家!

R S*_*ahu 4

这是实现目标的最佳方式吗?

如果你确定向量的向量会比 更长久psPtr,那么是的。否则,您将面临包含无效指针的风险psPtr

在这种情况下,我可以通过使用迭代器或某些 std 方法来摆脱“新删除”的事情吗?

是的。我建议使用:

std::vector<short*> psPtr(vvsVec.size());
Run Code Online (Sandbox Code Playgroud)

然后&psPtr[0]在调用C API函数时使用。这消除了代码中内存管理的负担。

foo(&psPtr[0]);        
Run Code Online (Sandbox Code Playgroud)