假设我有一个 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;
}
这是实现目标的最佳方式吗?在这种情况下,我可以通过使用迭代器或某些 std 方法来摆脱“新删除”的事情吗?提前致谢。
Edit:根据答案,我现在使用这个版本与 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++。感谢大家!