如何使用基于范围的循环来重写此代码
How do I rewrite this code using range-based for loops?
我是C 的新手,现在我被介绍给C 11。我发现语法非常不同,我需要一些帮助重写以下代码。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector<int> > magic_square ={{1, 14, 4, 15}, {8, 11, 5, 10},
{13, 2, 16, 3}, {12, 7, 9, 6}};
for(inti=0; i<magic_square.size(); i++)
{
int sum(0);
for(intj=0; j<magic_square[i].size(); j++)
sum += magic_square[i][j];
if(sum!=34)
return-1;
}
cout << "Square is magic" << endl;
return0;
}
您可以通过使用std::accumulate
完全消除内部循环,然后简单地将外循环基于范围:
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<std::vector<int>> magic_square = {{1, 14, 4, 15}, {8, 11, 5, 10}, {13, 2, 16, 3}, {12, 7, 9, 6}};
for (auto& v : magic_square)
{
if ( std::accumulate(v.begin(), v.end(), 0) != 34 )
return-1;
}
std::cout << "Square is magicn";
return 0;
}
实时示例
你去那里:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
static constexpr auto SUM= 34;
vector<vector<int>> magic_square= {
{ 1, 14, 4, 15},
{ 8, 11, 5, 10},
{13, 2, 16, 3},
{12, 7, 9, 6}
};
for (const auto& row: magic_square) { // auto not to type the type,
// const because you do read only and &
// to use reference and avoid copying
auto sum= 0; // Auto with integer defaults to int
for(const auto& number: row) { // Now for every number on the row
sum+= number;
}
if (sum != SUM) {
return 1;
}
}
cout << "Square is magic" << endl;
return 0;
}
您可以运行它:https://ideone.com/jq346v
相关文章:
- 如何循环打印顶点结构
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何使用基于范围的循环来重写此代码
- 如何将3个嵌套循环重写为一个
- 如何将基于迭代器的 for 循环重写为基于范围的循环 (C++11)
- 我是否应该重写循环标头以迭代 STL 向量
- 如何使用 C++ STL 算法重写嵌套循环
- 如何从重写的运算符循环访问矢量数据成员<<
- 重写这个循环
- c++在循环中重写函数
- 在while循环的下一次迭代中重写Const char *