如何将2D阵列的元素复制到1D向量上

How do I copy the elements of a 2D array onto a 1D vector?

本文关键字:复制 1D 向量 元素 2D 阵列      更新时间:2023-10-16

所以我一直试图转移元素,但它一直给我重复的元素,它无法将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];
    }
}

通常,如果您有一个二维数组,并且希望复制矢量中每行元素的nRowsnCols,则可以使用标头<algorithm> 中声明的标准算法std::copy

例如

auto it = x.begin();
for ( int i = 0; i < nRows; i++ ) 
{
    it = std::copy( matrix[i], matrix[i] + nCols, it ); 
}