将2维数组的所有元素插入1维数组

时间:2018-10-13 01:28:54

标签: c++ arrays copy

您好亲爱的社区

我正在使用c ++数组(静态和动态数组)。我的静态数组A1的大小为[30] [30],而我的动态数组A2的长度为[30 * 30]。 我想要做的是将A1复制到A2中。

数组A1A2的内容用0到9之间的随机整数填充。

这是我以前的解决方法:(我认为到目前为止,我已将副本复制到A2中,但是我不知道如何返回数组A2。)

int main() {
    //Array 2-Dimensional
    int A1[30][30] = { 0 };
    int *A2 = new int[30*30];
    int x, j, z;

    for (x = 0; x < 30; x++) {
        for (j = 0; j < 30; j++) {
            A1[x][j] = rand() % 10;
            printf("%d ", A1[x][j]);
            for (z = 0; z < 30 * 30; z++) {
                A2[z] = A1[x][j]; 
            }
        }
        printf("\n");           
    }
    system("Pause");
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您不需要三个嵌套循环即可实现此目的。诀窍是使用静态数组的两个索引来计算动态数组的索引。

这里是一个完整的示例,说明如何使用两个嵌套循环在C ++中执行此操作:

#include <iostream>

const constexpr static int SIZE = 30;

int main() {
    int A1[SIZE][SIZE] = { 0 };
    int *A2 = new int[SIZE * SIZE];

    for (int row = 0; row < SIZE; row++) {
        for (int col = 0; col < SIZE; col++) {
            A1[row][col] = rand() % 10;
            std::cout << A1[row][col] << ' ';

            // calculates the index for A2
            int index = row * SIZE + col;
            A2[index] = A1[row][col];
        }
        std::cout << '\n';
    }

    // A simple loop just to print the contents of A2
    for (int i = 0; i < SIZE * SIZE; i++) {
        std::cout << A2[i] << ' ';
    }

    // don't forget to deallocate A2
    delete[] A2;

    return 0;
}

答案 1 :(得分:0)

等等。哪种语言?? C ++?

#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <array>
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    constexpr std::size_t num_elements{ 30 };
    constexpr std::size_t max_idx{ num_elements - 1 };

    std::array<std::array<int, num_elements>, num_elements> A1;
    std::vector<int> A2(num_elements * num_elements);

    std::srand(static_cast<unsigned>(std::time(nullptr)));
    std::generate(&A1[0][0], &A1[max_idx][max_idx] + 1, [](){ return rand() % 10; });

    for (auto const &row : A1) {
        for (auto const &col : row)
            std::cout << col << ' ';
        std::cout.put('\n');
    }

    std::copy(&A1[0][0], &A1[max_idx][max_idx] + 1, A2.begin());

    for (auto const &i : A2)
        std::cout << i << ' ';
}
相关问题