如何使用基于范围的循环来重写此代码

How do I rewrite this code using range-based for loops?

本文关键字:循环 重写 代码 范围 何使用 于范围      更新时间:2023-10-16

我是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