2

I created a simple struct object that holds 2 values - number (specific number) and count (counter for how many times number appears).

typedef struct matrixMissNumber {
  int number;
  int count = 0;
}

Then I created a list called, missingNumsObjects, to hold those objects. missNums is a seprate list that simply holds ints.

list<matrixMissNumber> missingNumsObjects;
for (auto m : missNums)
{
    matrixMissNumber mn;
    mn.number = m;
    missingNumsObjects.push_back(mn);
}

I then have 3 for-loops that go through and check 2 conditions. If those conditions are satisfied, count increments by 1. (I added a cout statement for testing purposes). I debugged the program and everything works perfectly, until the loops end. That's when the count variable for every matrixMissNumber object in missingNumsObjects resets back to 0. I'm not sure if its a problem where different memory addresses are being manipulated, or lists pointers that are the issue.

for (auto m : missingNumsObjects)
{
    for (int x = 0; x < 3; x++)
    {
        for (int y = 0; y < 3; y++)
        {
            if (sudoku[x][y] == 0)
            {
                if (checkRowRule(m.number, x) == false && checkColumnRule(m.number, y) == false)
                {
                    m.count++;
                    cout << m.number << " - " << m.count << endl;
                }
            }
        }
    }
}

The next lines print out the values of count of the missingNumsObjects after the loop. This is where the values return back to 0.

for (auto m : missingNumsObjects)
    cout << m.number << " - " << m.count << endl;

This program's purpose is a Sudoku Solver. This part of the algorithm checks the 3x3 matrix for missing numbers and checks into how many empty spots in the 3x3 matrix that number can go into.

2 Answers2

11
for (auto m : missingNumsObjects)

Here auto is deduced as matrixMissNumber, so m is a copy of matrixMissNumber object stored in the list. Then you change the copy, not the object in the list missingNumsObjects.

To fix the issue help the compiler to deduce the type properly and change the cycle to:

for (auto& m : missingNumsObjects)
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
  • Thanks! works as planned now. I just recently got back to using C++ and I've only now started using "for (auto x: name)". Will definitely keep that in mind for next time I use it – Liel van der Hoeven Aug 02 '17 at 15:41
0

The problem you'll gain the most from is actually here

"I debugged the program and everything works perfectly, until the loops end".

Things weren't working perfectly until the loop finished. You never inspected the contents of the list as had you done so, you'd have noticed that it never changed.

The moral of this is that when debugging, inspect the thing that should be changing, not what you're assigning to.

UKMonkey
  • 6,941
  • 3
  • 21
  • 30