Range based for loop

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.
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.


Here is what I have so far.
1
2
3
4
5
6
7
8
	for (const auto& <vector<int>> : magic_square)
	{
		int sum(0);
		for (int j = 0; j < magic_square[i].size(); j++)
			sum += magic_square[i][j];
		if (sum != 34)
			return -1;
	}


This is for an assignment. I can't figure out what to do.
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
This is what I have so far, not sure if it is correct

1
2
3
4
5
6
7
8
9
10
for (const auto& inner_vec : magic_square)
	{
		int sum(0);
		for (int element : inner_vec)
		{
			sum += magic_square[inner_vec][inner_vec];
		}
		if (sum != 34)
			return -1;
	}
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.
Topic archived. No new replies allowed.