假设我有一个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方法来删除“新删除”的内容吗?提前谢谢。
编辑:,根据答案,我现在使用这个版本与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++。谢谢大家!
发布于 2017-02-22 19:21:48
这是实现目标的最佳方式吗?
如果你确信向量的向量将超过psPtr,那么是的。否则,您将面临psPtr包含无效指针的风险。
在这种情况下,我可以使用迭代器或一些std方法来删除“新删除”的内容吗?
是。我建议使用:
std::vector<short*> psPtr(vvsVec.size());然后在调用call函数时使用&psPtr[0]。这将从代码中消除内存管理的负担。
foo(&psPtr[0]); 发布于 2017-02-22 19:22:20
std::vector<short*> vecOfPtrs;
for (auto&& vec : vvsVec)
vecOfPtrs.push_back(&vec[0]);
foo(&vecOfPtrs[0]);https://stackoverflow.com/questions/42400272
复制相似问题