r/programminghelp • • Feb 26 '21

C++ Need help editing class variables with a for loop in C++

Essentially I am trying to assign values to variables of multiple objects at once.

This is what I thought would work but doesn't seem to work:

Puzzle puzzle1; Puzzle puzzle2; Puzzle puzzle3; Puzzle puzzles[3] = {puzzle1, puzzle2, puzzle3};

for (int i = 0; i < 6; i++) { puzzles[i].width = 3; }

I've been alternating between different projects in c++ and Python, maybe I'm mixing syntax?

Thanks in advance!

4 Upvotes

5 comments sorted by

1

u/jedwardsol Feb 26 '21

puzzles only has 3 elements, so writing to 6 of them is a bug.

The Puzzle objects in puzzles are copies of puzzle1, puzzle2 and puzzle3. So thr 3 names objects won't be altered by the loop.

If you want 3 objects to loop over, ditch the 3 named ones and keep just the array

1

u/brightstar537 Feb 26 '21

sorry that was just a typo, it isn't present in my actual code. In the real code it's for (int i = 0; i < 3 , etc.

oh I see, so I can eliminate the initiation of the other 3 puzzle objects as they are created and stored in the array automatically?

Thanks a ton!

1

u/[deleted] Feb 26 '21

Alternatively you could make puzzles an array of puzzle references.

1

u/brightstar537 Feb 26 '21

How would I do that?

Sorry I'm fairly new

1

u/Coulomb111 Mar 21 '21

I know this was already answered, but use std::vector instead of that type of array.

It would look like this:

using namespace std;

Puzzle puzzle1; Puzzle puzzle2; Puzzle puzzle3;

vector<Puzzle> puzzles = { puzzle1, puzzle2, puzzle3 };

for (Puzzle &puzzle : puzzles) { puzzle.width = 3; }