簡體   English   中英

如何使用基於范圍的for循環重寫此代碼?

[英]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 magic\n";
   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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM