[英]How do I rewrite this code using range-based for loops?
I am new to C++ and now I have been introduced to C++11. 我是C ++的新手,现在已被介绍给C ++ 11。 I find the syntax very different and I need some help rewriting the following code. 我发现语法非常不同,我需要一些帮助来重写以下代码。
#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;
}
You could eliminate the inner loop altogether by using std::accumulate
and simply have the outer loop be range-based: 您可以通过使用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 magic\n";
return 0;
}
There you go: 你去了:
#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;
}
You can run it in: https://ideone.com/JQ346v 您可以在以下位置运行它: https : //ideone.com/JQ346v
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.