Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class IndeX cpp?

lets say my code looks like this:

[...]
class klasse{
public: 
int Var1;
int Var2;
};

klasse Klasse1;
klasse Klasse2;
klasse Klasse3;



Klasse1.Var1=1;
Klasse2.Var1=1;
Klasse3.Var1=1;
//now watch 
if(Klasse1.Var1==1)
{
Klasse1.Var2=1;
}
if(Klasse2.Var1==1)
{
Klasse2.Var2=1;
}
if(Klasse2.Var1==1)
{
Klasse2.Var2=1;
}

U understand the Problem?
i want to have a For-loop for the VaribleNames
Like this:

[...]
class klasse{
public: 
int Var1;
int Var2;
};


klasse Klasse1;
klasse Klasse2;
klasse Klasse3;



Klasse1.Var1=1;
Klasse2.Var1=1;
Klasse3.Var1=1;

for(int i=0; i<3; i++)
{
if(Klasse[i].Var1==1)
{
Klasse[i].Var2=1;
}
}

i tryed to do it with a vector but it does not work correcly, or how it shoud work, maybe im just to incompetent for that

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your idea of using a vector is a good one.

int main(void) {
    std::vector<klasse> klasses(3);

    for (int i=0; i<3; i++)
        klasses[i].var1 = 1;

    for (int i=0; i<3; i++)
        if (klasses[i].var1 == 1)
            klasses[i].var2 = 1;
}

Alternative, you could use range-based for loops:

    for (auto &k : klasses)
       if (k.var1 == 1)
           k.var2 = 1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading