I am new to C++ and now I have been introduced to 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:
#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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.