使用单循环打印矩阵的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
此外,当矩阵是矩形时它不起作用
一种方法是:
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)]<<" ";
}
}
相关文章:
- 部分定义/别名模板模板参数
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- 程序在执行程序的其余部分之前退出
- 在更改for循环的第三部分后,未使用for循环结果
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 部分专业化和嵌套模板
- 为C++03编译器编写部分unique_ptr,该编译器与较新的编译器在公共代码库上运行
- 如何将数组部分初始化为某个默认值?
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- 在疯狂的部分中声明变量
- 由于PC显示设置的更改,Qt小部件被部分剪裁
- 在未链接的部分上生成警告
- 是同一作用域的函数部分中的函数调用
- C++:部分模板专用化用例
- 部分专业化和对标准::void_t<>的需求
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 使用对象的基类部分模板专用化对对象进行哈希处理::哈希
- C++ 初始化 .data 部分中的变量
- 使用单循环打印矩阵的L部分