如何将整数数组的向量转换为C 中的2D数组
How to convert a vector of integer arrays into a 2D array in C++?
,所以我一直在研究以下帖子,以将向量转换为数组,但是此方法似乎并未转换为我的用例。
如何将向量转换为数组
vector<array<int, 256>> table; // is my table that I want to convert
// There is then code in the middle that will fill it
int** convert = &table[0][0] // is the first method that I attempted
convert = table.data(); // is the other method to convert that doesn't work
我相信我对数据类型后端的理解是我的知识不足。对此的任何帮助将不胜感激
编辑:我已将表格C样式数组更改为C 数组
虽然应该有一条应通过铸造来工作的路线,但我可以保证的最简单的事情是将一系列指针送到 int
s,其中包含指向阵列的指针源vector
。
// make vector of pointers to int
std::vector<int*> table2(table.size());
// fill pointer vector pointers to arrays in array vector
for (int i = 0; i < size; i++ )
{
table2[i] = table[i];
}
示例:
#include <vector>
#include <iostream>
#include <iomanip>
#include <memory>
constexpr int size = 4;
// test by printing out
void func(int ** arr)
{
for (int i = 0; i < size; i++ )
{
for (int j = 0; j < size; j++ )
{
std::cout << std::setw(5) << arr[i][j] << ' ';
}
std::cout << 'n';
}
}
int main()
{
std::vector<int[size]> table(size);
// fill values
for (int i = 0; i < size; i++ )
{
for (int j = 0; j < size; j++ )
{
table[i][j] = i*size +j;
}
}
// build int **
std::vector<int*> table2(table.size());
for (size_t i = 0; i < size; i++ )
{
table2[i] = table[i];
}
//call function
func(table2.data());
}
看来您是因为对int **
的要求而陷入困境,但请尝试使用简单的矩阵类。
假设使用C 11,include <algorithm>
您可能可以使用std ::复制。
我没有测试过,但相信您可以做:
std::copy(&table[0][0], &table[0][0]+256*table.size(), &myArray[0][0]);
参数有效:
std::copy(<source obj begin>, <source obj end>, <dest obj begin>);
在此处进行更多信息:https://en.cppreference.com/w/cpp/algorithm/copy
相关文章:
- 试图让变量检查数组中的某些内容
- 使用for循环检查数组中的重复项
- 对字符数组中的元素执行逐位操作
- 按平均值替换数组中的元素
- 移动二维数组中的字符
- 打印矢量数组中的所有元素
- 字符数组中的元素数
- 使用指针访问数组中的对象数据成员
- 显示数组中的学生 ID 和最高分
- C++数组中的 GLFloat 数组
- C++ 使用存储在动态数组中的文本文件中的数据查找模式
- 在 C++ 中搜索动态分配的数组中的出现次数
- 如何在 c++ 中格式化和访问 2D 矢量数组中的数据
- 使用 GDAL 获取矢量数组中的所有行数和列数
- 关于字符数组,我正在尝试将数组中的每个字符分配给另一个值
- C++递归来决定数组中的两个值
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- 在C++中访问结构数组中的数据
- 如何在 C++ 中将双精度数组中的值"force convert"到字符串输出中?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?