将向量的向量转换为指针的指针

Convert vector of vector to pointer of pointer

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

#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;
}

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

编辑: 根据答案,我现在使用这个版本来与 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;
}

在我看来更像 C++。谢谢大家!

Is this the best way to achieve the goal?

如果您确定矢量的矢量会比 psPtr 长寿,那么是的。否则,您 运行 将面临 psPtr 包含无效指针的风险。

Can I get rid of the "new delete" thing by using iterator or some std method in this case?

是的。我建议使用:

std::vector<short*> psPtr(vvsVec.size());

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

foo(&psPtr[0]);        
std::vector<short*> vecOfPtrs;
for (auto&& vec : vvsVec)
    vecOfPtrs.push_back(&vec[0]);

foo(&vecOfPtrs[0]);