如何将2D阵列的元素复制到1D向量上
How do I copy the elements of a 2D array onto a 1D vector?
所以我一直试图转移元素,但它一直给我重复的元素,它无法将2D阵列正确复制到1D矢量上
// This was one of my attempts
vector<int> rando(int rowsize, int columnsize)
{
int elements = rowsize*columnsize;
vector<int> x(elements);
int matrix[100][100];
for(int i = 0; i < rowsize; i++)
{
for(int j = 0; j < columnsize; j++)
{
srand((int)time(0));
matrix[i][j]= -10 + rand() % 21;
for(int n=0; n < elements; n++)
x[n]=matrix[i][j];
}
// Ive also tried this
for(int n=0; n < elements; n++)
{
for(int i = 0; i < rowsize; i++)
{
for(int j = 0; j < columnsize; j++)
{
x[n]=matrix[i][j];
}
}
}
}
return x;
}
为什么要先将数据存储到矩阵中,然后再将其复制到向量中?从一开始就使用矢量。
std::vector<int> rando(std::size_t rowsize, std::size_t columnsize)
{
std::vector<int> v(rowsize*columnsize);
std::mt19937 mt{std::random_device{}()};
std::uniform_int_distribution<int> rand_dist(-10, 10);
for (auto & e : v) e = rand_dist(mt);
return v;
}
如果你想把数据从矩阵转移到向量中,你必须计算正确的索引,或者像托马斯·马修斯建议的那样只增加一个变量。
constexpr std::size_t n = 100, m = 100;
int matrix[n][m];
// do stuff with matrix
std::vector<int> v(n*m);
for (std::size_t i=0; i<n; ++i)
{
for (std::size_t j=0; j<m; ++j)
{
v[i*m + j] = matrix[i][j];
}
}
通用副本应该循环通过2个维度,并且在每次迭代时只增加目标索引(没有第三个嵌套循环):
int n=0;
for(int i = 0; i < rowsize; i++)
{
for(int j = 0; j < columnsize; j++)
{
...
x[n++]=matrix[i][j]; // not in an additional for loop !!
}
} // end of initialisation of matrix
如果您的矩阵是2D阵列(即连续元素),您也可以使用<algorithm>
:使用以下快捷方式
copy (reinterpret_cast<int*>(matrix), reinterpret_cast<int*>(matrix)+elements, x.begin());
试试这个:
unsigned int destination_index = 0;
for(int i = 0; i < rowsize; i++)
{
for(int j = 0; j < columnsize; j++)
{
x[destination_index++]=matrix[i][j];
}
}
每次分配到新插槽后,目标索引都会递增
不需要第三个循环。
使用两个循环就足够了。
例如
srand((int)time(0));
for(int i = 0; i < rowsize; i++)
{
for(int j = 0; j < columnsize; j++)
{
matrix[i][j]= -10 + rand() % 21;
x[i * columnsize + j] = matrix[i][j];
}
}
通常,如果您有一个二维数组,并且希望复制矢量中每行元素的nRows
和nCols
,则可以使用标头<algorithm>
中声明的标准算法std::copy
例如
auto it = x.begin();
for ( int i = 0; i < nRows; i++ )
{
it = std::copy( matrix[i], matrix[i] + nCols, it );
}
相关文章:
- 1d 智能指针不适用于语法 (*)++
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 使用strcpy将char数组的元素复制到另一个数组
- 是否可以初始化不可复制类型的成员变量(或基类)
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 复制列表初始化的隐式转换的等级是多少
- 当从函数参数中的临时值调用复制构造函数时
- 有可能在Armadillo中复制MATLAB circshift方法吗
- C++使用数组作为多维数组,尽管将其初始化为带有指针的 1D
- 复制几乎为空的数组的最快方法
- 以下示例中如何避免代码复制?C++/库达
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 如何使用指针C++将元素从2D数组复制到1D数组
- 从 2D 数组复制(行)到 1D 数组
- 如何使用c++将2D矩阵的元素垂直复制到1D阵列
- 如何将2D阵列的元素复制到1D向量上
- CUDA:分配1d设备内存来将2d指针到指针主机数组复制到GPU