Files
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

45 lines
1.6 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
// https://www.bilibili.com/video/BV1iC4y1p77u
// 要想理解明白,需要画图,按视频的图来理解就简单明白了
//动态二维数据应用:行列转换
using namespace std;
int y[101]; //y[i]:第i个数据所在的列
int c[101]; //c[j]:第j列的数据个数
int main() {
int i, j, M = 5, K = 8;
int w[8][3] = {{1, 2, 12},
{1, 4, 14},
{2, 2, 22},
{2, 5, 25},
{3, 4, 34},
{4, 1, 41},
{4, 3, 43},
{4, 5, 45}};
//读入数据到我们定义的数据结构中其实就是两个数组模拟一个M*N的大数组有数据的留用无数据的不占用资源
for (i = 1; i <= K; i++) {
y[i] = w[i - 1][1];//列
c[y[i]]++;//每列数据个数
}
//给指针a申请M+1个int型指针空间
int **a = new int *[M + 1];//指针数组 a指向指针数组的开头
//给第i列指针a[i]申请c[i]个int型空间
for (i = 1; i <= M; i++)a[i] = new int[c[i]];//放弃a[0],从a[1]开始创建动态数组数组的大小就是c[i]
//收集k个数据到相应的y[i]列中
for (i = 1; i <= K; i++) {
*a[y[i]] = w[i - 1][2]; //向指针指向的数组元素进行赋值
printf("*a[%d]=%d\n", y[i], *a[y[i]]);
a[y[i]]++;//数组指针下移,
}
//列优先输出数据
for (i = 1; i <= M; i++) {
a[i] -= c[i];//数组指针回到每列前面
for (j = 1; j <= c[i]; j++, a[i]++)
printf("%d ", *a[i]);//输出数据
}
return 0;
}