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

C++如何将数组指定下标元素移动到所有位置并输出全部对应数组

解法说明
  • 原有代码的核心问题:直接修改原数组会导致后续操作基于已经被更改的数组运行,无法得到正确结果。正确的做法是每次生成排列时都基于未被修改的原始数组操作,避免原数据被污染。
  • 实现步骤:
    1. 预先保存原始数组的副本,同时提取待移动的目标元素
    2. 遍历所有16个目标插入位置,每个位置对应一种排列结果
    3. 对每个目标位置,按照逻辑生成新数组后打印即可,不需要单独判断左右移位,降低出错概率
完整实现代码
#include <iostream>
using namespace std;

int main() {
    const int ARRAY_LEN = 16;
    // 原始数组,全程不会被修改
    int original_arr[ARRAY_LEN] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
    int givenIndex = 6;
    int target_val = original_arr[givenIndex];

    // 遍历所有可能的插入位置,共16种
    for (int insert_pos = 0; insert_pos < ARRAY_LEN; insert_pos++) {
        int temp_arr[ARRAY_LEN];
        int temp_idx = 0;
        for (int i = 0; i < ARRAY_LEN; i++) {
            // 到了插入位置先放目标元素
            if (i == insert_pos) {
                temp_arr[temp_idx++] = target_val;
            }
            // 跳过原始数组里原位置的目标元素,其他元素按顺序写入
            if (i != givenIndex) {
                temp_arr[temp_idx++] = original_arr[i];
            }
        }
        // 打印当前结果
        cout << "[";
        for (int k = 0; k < ARRAY_LEN; k++) {
            if (k != 0) cout << ",";
            cout << temp_arr[k];
        }
        cout << "]" << endl << endl;
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 12:15:04