有没有办法将"std::vector 2d"作为指向函数的"2d c 数组"的指针传递
Is there a way to pass 'std::vector 2d' as a pointer to '2d c array' to a function
是否有方法将"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] );
相关文章:
- 如何在C++函数中声明静态 2D 数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 将 2D 推力::d evice_vector 复矩阵传递给 CUDA 内核函数
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 使用指针算法修改函数中的 2D 数组
- 交换函数不是在 C++ 中交换 2D 数组的元素
- 无法分配函数指针的 2D 数组
- 无法将 2D 数组传递到 c++ 中的帮助程序函数中
- 打印 2D 动态数组 c++ 函数
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 在 c 和 c++ 中将 2D 数组传递给函数
- 如何创建一个接受2D数组的构造函数
- 我怎么能有一个以2D数组为参数的函数,而数组有一个我想更改的参数/维度
- C++尝试告诉函数要使用哪个 2D 数组
- 如何将 2D 数组传递到函数 (C++)中?
- 将 2D 数组指针传递给 C++ 中的函数
- 将直方图的 2D 数组传递给函数 (C++)?
- 我无法在函数中动态分配 2D 数组
- 2D函数最小化算法或C/C 库