r/programminghelp • u/brightstar537 • 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!
1
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; }
1
u/jedwardsol Feb 26 '21
puzzlesonly has 3 elements, so writing to 6 of them is a bug.The Puzzle objects in
puzzlesare copies ofpuzzle1,puzzle2andpuzzle3. 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