博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多维矩阵转一维数组(c++)【转载】
阅读量:2289 次
发布时间:2019-05-09

本文共 1034 字,大约阅读时间需要 3 分钟。

在由二维矩阵转为一维数组时,我们有两种方式:以列为主和以行为主。

以列为主的二维矩阵转为一维数组时,转换公式为:

index=column+row×行数

以行为主的二维矩阵转为一维数组时,转换公式为:

index=row+column×列数

   

#include<iostream>

#include <iomanip>

using namespace std;

int main()

{

      int arr1[3][4] = { { 1, 2, 3, 4 },

                         { 5, 6, 7, 8 },

                         { 9, 10, 11, 12 }

                       };

      int arr2[12] = { 0 };

      int row, column, index;

      cout << "原二维资料:" << endl;

      for (row = 0; row < 3; row++)

      {

            for (column = 0; column < 4; column++)

                  cout << setiosflags(ios::left) << setw(4) << arr1[row][column];

            cout << endl;

      }

      cout << "以列为主:" << endl;

      for (row = 0; row < 3; row++)

      {

            for (column = 0; column < 4; column++)

            {

                  index = column + row * 4;

                  arr2[index] = arr1[row][column];

            }

      }

      for (int i = 0; i < 12; i++)

            cout << setw(4)<<arr2[i] << " " ;

      cout << endl;

      cout << "以行为主:" << endl;

      for (row = 0; row < 3; row++)

      {

            for (column = 0; column < 4; column++)

            {

                  index = row + column * 3;

                  arr2[index] = arr1[row][column];

            }

      }

      for (int i = 0; i < 12; i++)

            cout << setw(4) << arr2[i] << " ";

      cout << endl;

      return 0;

}

转载于:https://www.cnblogs.com/liusuanyatong/p/11259908.html

你可能感兴趣的文章
为什么我的系统没有asoundlib.h文件?
查看>>
git实现公共仓库
查看>>
Linux系统下查看目录大小
查看>>
Win32API大全
查看>>
Python字典、列表排序
查看>>
ELF,COFF,PE
查看>>
MinGW Static and Dynamic Libraries
查看>>
调用dll
查看>>
Linux统计文件行数
查看>>
linux查看文件和文件夹大小
查看>>
linux下C获取文件的大小
查看>>
linux C文件到文件,文件到文件夹,文件夹到文件夹的拷贝
查看>>
linux grep命令
查看>>
Linux GCC常用命令
查看>>
linux环境变量set env export细解
查看>>
Python之os.walk和os.path.walk
查看>>
python 之 分割参数getopt
查看>>
内存映射文件原理探索
查看>>
linux shell 字符串操作
查看>>
shell 逻辑运算符、逻辑表达式
查看>>