You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++将两个一维数组复制到多维数组的实现疑问

把两个一维数组复制到多维数组的C++实现

嘿,刚接触平台发帖完全没问题,操作不当很正常,别担心~关于把两个一维数组复制到多维数组的问题,我给你几种常见的实现方式,你可以根据自己的代码场景来选:

方式一:静态数组 + 标准库std::copy(适合固定长度数组)

这种方式代码简洁高效,适合数组长度提前确定的场景:

#include <iostream>
#include <algorithm> // 引入std::copy所需头文件

int main() {
    // 定义两个待复制的一维数组
    int arr1[] = {1, 2, 3, 4};
    int arr2[] = {5, 6, 7, 8};
    const int rowCount = 2; // 多维数组行数,对应一维数组的数量
    const int colCount = 4; // 多维数组列数,对应一维数组的长度

    // 声明二维数组
    int multiArray[rowCount][colCount];

    // 复制第一个一维数组到多维数组第一行
    std::copy(arr1, arr1 + colCount, multiArray[0]);
    // 复制第二个一维数组到多维数组第二行
    std::copy(arr2, arr2 + colCount, multiArray[1]);

    // 验证复制结果
    for (int i = 0; i < rowCount; ++i) {
        for (int j = 0; j < colCount; ++j) {
            std::cout << multiArray[i][j] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

代码说明:

  • std::copy是C++标准库提供的元素复制函数,它会把[arr1, arr1+colCount)区间内的元素,复制到multiArray[0]指向的内存位置(也就是二维数组第一行的起始地址)。
  • multiArray[0]本质是指向int类型的指针,和一维数组的首地址类型一致,所以可以直接作为std::copy的目标参数。

方式二:手动循环复制(适合理解底层逻辑)

如果想更清晰地掌握复制的底层过程,手动写循环会更直观:

#include <iostream>

int main() {
    int arr1[] = {1, 2, 3, 4};
    int arr2[] = {5, 6, 7, 8};
    const int rowCount = 2;
    const int colCount = 4;
    int multiArray[rowCount][colCount];

    // 复制arr1到多维数组第一行
    for (int j = 0; j < colCount; ++j) {
        multiArray[0][j] = arr1[j];
    }

    // 复制arr2到多维数组第二行
    for (int j = 0; j < colCount; ++j) {
        multiArray[1][j] = arr2[j];
    }

    // 打印结果
    for (int i = 0; i < rowCount; ++i) {
        for (int j = 0; j < colCount; ++j) {
            std::cout << multiArray[i][j] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

方式三:动态容器std::vector(适合长度不固定的场景)

如果你的数组长度是动态变化的,用C++的std::vector会更灵活:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> arr1 = {1, 2, 3, 4};
    std::vector<int> arr2 = {5, 6, 7, 8};

    // 创建二维vector,包含2行,每行长度和arr1一致
    std::vector<std::vector<int>> multiArray(2, std::vector<int>(arr1.size()));

    // 复制元素
    std::copy(arr1.begin(), arr1.end(), multiArray[0].begin());
    std::copy(arr2.begin(), arr2.end(), multiArray[1].begin());

    // 验证结果
    for (const auto& row : multiArray) {
        for (int num : row) {
            std::cout << num << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

上面几种方式都能满足你的需求,你可以根据作业里的数组类型(静态/动态)来选择合适的方法~

内容的提问来源于stack exchange,提问作者Chris Ammen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:42:55