简体   繁体   English

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

[英]Print L part of a matrix using single loop

Let the given matrix is 让给定的矩阵为

{1,2,4} {1,2,4}

{3,4,6} {3,4,6}

{7,8,9} {7,8,9}

It should print 1 3 7 8 9 using single loop. 它应该使用单循环打印1 3 7 8 9。

I have tried like this 我已经试过了

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

But it would print 1 7 3 8 9 但它会打印1 7 3 8 9

moreover it would not work when matrix is rectangular 此外,当矩阵为矩形时,它将不起作用

I'm not sure why you'd want to do this but one way would be: 我不确定为什么要这样做,但是一种方法是:

#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)]<<" ";
    }
}

One way would be: 一种方法是:

    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];
        }
    }

where N = number of lines and M = number of columns. 其中N =行数,M =列数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM