May 20, 2020 at 7:46pm UTC
I am a bit stuck on this question
#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 (int i=0; i<magic_square.size(); i++)
{
int sum(0);
for(int j=0; j<magic_square[i].size(); j++)
sum += magic_square[i][j];
if(sum!=34)
return -1;
}
cout << "Square is magic" << endl;
return 0;
}
Rewrite the above code using range-based for loops.
I have been reading up about the range-based for loops but I still don't think I completely understand it.
May 20, 2020 at 7:49pm UTC
Show us what you've tried.
By the way it will be easier to understand if you start with a single dimensional vector.
And please use code tags when posting code.
May 20, 2020 at 8:10pm UTC
magic_square is a vector of vectors.
So when you iterate through the outer vectors, you then need to iterate through each inner vector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Example program
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
int main()
{
vector<vector<int >> vec = {
{ 1, 2, 3, 4, 5 },
{ 6, 7, 8, 9 },
{ 3, 22, 84, 19, 27, 28 }
};
for (const auto & inner_vec : vec)
{
for (int element : inner_vec)
{
cout << element << ' ' ;
}
cout << '\n' ;
}
}
Last edited on May 20, 2020 at 8:11pm UTC
May 20, 2020 at 9:16pm UTC
When using range based for loops, you are working with the actual values from the containers--not indexes. So, change line 6 to sum += element;
See if that works for you.