如何用0和1填充2D数组,其中第N行的每个第N个元素都是1,其余元素是0
How can I fill a 2D array with 0 and 1, where every Nth element of row N is a 1 and the rest is 0?
例如,第一行应该全部填充1。在第二行中,每一个第二个元素都应该用1填充,其他元素应该用0填充。在第三行中,每三个元素都应填充1,其他元素应填充0,依此类推
1, 1, 1, 1, 1, ...
1, 0, 1, 0, 1, ...
1, 0, 0, 1, 0, ...
1, 0, 0, 0, 1, ...
像往常一样,有很多方法可以完成任务。例如,您可以使用以下解决方案
#include <iostream>
int main()
{
const size_t M = 5;
const size_t N = 10;
int a[M][N];
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) a[i][j] = ( j + 1 ) % ( i + 1 ) == 0;
}
for ( const auto &row : a )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
程序输出为
1 1 1 1 1 1 1 1 1 1
0 1 0 1 0 1 0 1 0 1
0 0 1 0 0 1 0 0 1 0
0 0 0 1 0 0 0 1 0 0
0 0 0 0 1 0 0 0 0 1
如果您的编译器不支持基于范围的循环
for ( const auto &row : a )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
然后你可以用它来代替一个普通的循环。例如
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ ) std::cout << a[i][j] << ' ';
std::cout << std::endl;
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 如何用数字处理log(0)
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 如何用NaN元素初始化双矩阵?
- 如何用其中一个元素为联合来制作或制造_tuple
- 如何用指针擦除矢量元素
- 如何用0和1填充2D数组,其中第N行的每个第N个元素都是1,其余元素是0
- 如何用c++在sql连接中插入数组元素
- 如何用键盘改变glLookat视图元素的整数值
- cocos2dx c++如何用鼠标触控绘制线条(绘制元素)
- 如何用相同的参数初始化所有元组元素