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

如何使用map容器让代码输出指定循环移位的4×4数字矩阵

实现循环移位的4×4数字矩阵(C/C++方案)

首先要明确:C语言标准库没有map容器——那是C++ STL里的特性。如果是纯C语言开发,用二维数组就能轻松实现需求;如果是想尝试C++的std::map,我也给你对应的实现。


纯C语言实现(用二维数组,最适合新手)

这个方案逻辑简单,代码容易理解,完全贴合你的需求:

#include <stdio.h>

int main() {
    // 基础数组,存储第一行的1-4
    int base[4] = {1, 2, 3, 4};
    int matrix[4][4]; // 用来保存最终的4×4矩阵

    // 生成循环移位的矩阵
    for (int row = 0; row < 4; row++) {
        for (int col = 0; col < 4; col++) {
            // 核心逻辑:每往下一行,元素整体循环右移一位
            // 用(col + row) %4 获取base数组的对应下标,超出部分从开头取
            matrix[row][col] = base[(col + row) % 4];
        }
    }

    // 输出矩阵
    for (int row = 0; row < 4; row++) {
        for (int col = 0; col < 4; col++) {
            printf("%d ", matrix[row][col]);
        }
        printf("\n");
    }

    return 0;
}

运行这段代码,就能输出你要的结果:

1 2 3 4 
2 3 4 1 
3 4 1 2 
4 1 2 3 

C++用std::map的实现

如果是想学习C++的容器用法,用std::map存储行号和对应行的元素,代码如下:

#include <iostream>
#include <map>
#include <vector>

int main() {
    // map的键是行号(1-4),值是该行的元素列表
    std::map<int, std::vector<int>> matrix_map;
    std::vector<int> base = {1, 2, 3, 4};

    // 生成每行元素并存入map
    for (int row = 0; row < 4; row++) {
        std::vector<int> current_row;
        for (int col = 0; col < 4; col++) {
            current_row.push_back(base[(col + row) % 4]);
        }
        matrix_map[row + 1] = current_row; // 行号从1开始对应题目中的第一行
    }

    // 遍历map输出矩阵
    for (auto& entry : matrix_map) {
        for (int num : entry.second) {
            std::cout << num << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

关键说明

  • 两种方案的核心逻辑都是(col + row) %4:每一行的元素,都是基础数组循环右移行号次数后的结果
  • 纯C语言里没有map,别硬用,数组是最适合这个场景的工具
  • 如果你之前的代码是重复输出四行1 2 3 4,只需要把生成每行元素的逻辑换成上面的核心代码就行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:55:20