有没有办法将"std::vector 2d"作为指向函数的"2d c 数组"的指针传递

Is there a way to pass 'std::vector 2d' as a pointer to '2d c array' to a function

本文关键字:2d 函数 数组 指针 std vector 有没有      更新时间:2023-10-16

是否有方法将"std::vector 2d"作为指向"2d c array"的指针传递给函数。

我知道您可以将std::vector 1d作为指向c数组的指针传递给某个函数。例如功能:

void foo(char* str); //requires the size of str to be 100 chars
std::vector<char> str_;
str_.resize(100);
foo(&str_[0]); //works

我想知道2d向量是否可能功能

void foo(char** arr_2d);

和矢量

std::vector<std::vector<char>> vector_2d;

我尝试了以下代码,但我遇到了一些与堆损坏有关的错误。

std::vector<std::vector<unsigned char>> vector_2d;
//assuming function expects the size of the vector to be 10x10  
vector_2d.resize(10);
for(int i=0;i<10;i++)
{
    vector_2d[i].resize(10);
}
foo(&vector_2d[0]);//error here

以下是您可以做的:

std::vector< std::vector<unsigned char> > vector_2d;
vector_2d.resize(10);
std::vector<unsigned char*> ptrs(vector_2d.size());
for(int i=0;i<10;i++)
{
    vector_2d[i].resize(10);
    ptrs[i] = &vector_2d[i][0];
}
foo(&ptrs[0]);

不,你不能那样做。原因是char**是指向char的指针的指针,而&vector_2d[0]是类型std::vector<char>*

我建议您更改函数的接口,以获取您的二维向量(您可能希望将其重新设计为一个类,该类包含单个std::vector<char>,并提供operator()(int x,int y)来访问缓冲区中的元素(x,y)。或者,您可以根据需要创建所需的数据结构:

std::vector<std::vector<char> > data2d;
std::vector<char *> iface_adapter;
iface_adapter.reserve(data2d.size());
for ( unsigned int i = 0; i < data2d.size(); ++i ) {
   iface_adapter.push_back( &data2d[i][0] );
}
foo( &iface_adapter[0] );