使用单循环打印矩阵的L部分

Print L part of a matrix using single loop

本文关键字:部分 单循环 打印      更新时间:2023-10-16

设给定矩阵为

{1,2,4}

{3,4,6}

{7,8,9}

它应该使用单循环打印 1 3 7 8 9。

我试过这样

for(int i=0;i<n;i++){
if(i!=n-1)
cout<<a[i][0]<<" ";
cout<<a[n-1][i]<<" ";
}

但它会打印 1 7 3 8 9

此外,当矩阵是矩形时它不起作用

一种方法是:

for(int i = 0; i < N+M-1; i++)
{
if(i < N)
{
std::cout << std::endl << a[i][0];
}
else
{
std::cout << " " << a[N-1][i-N+1];
}
}

其中 N = 行数,M = 列数。

我不确定你为什么要这样做,但一种方法是:

#include <array>
#include <iostream>
#include <algorithm>
int main()
{
const int width = 3;
const int height = 4;
const std::array<std::array<int, width>, height> a = 
{{
{ 1, 2, 4 },
{ 3, 4, 6 },
{ 7, 8, 9 },
{ 10, 11, 12 },
}};
for(int i=0;i<width + height - 1;i++){
std::cout<<a[std::min(i, height - 1)][std::max(0, i - height + 1)]<<" ";
}
}