簡體   English   中英

使用單循環打印矩陣的L部分

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

讓給定的矩陣為

{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

此外,當矩陣為矩形時,它將不起作用

我不確定為什么要這樣做,但是一種方法是:

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

一種方法是:

    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 =列數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM