Is there a better way of writing this?

1
2
3
4
5
6
if (mon[0].isAlive() == false && mon[1].isAlive() == false && mon[2].isAlive() == false && mon[3].isAlive() == false && mon[4].isAlive() == false && mon[5].isAlive() == false
			&& mon[6].isAlive() == false && mon[7].isAlive() == false && mon[8].isAlive() == false && mon[9].isAlive() == false)
		{
			cout << "Killed all Monster " << endl;
			loop = false;
		}


Can I use a loop or something to check if all the monster objects in the array are dead and then show the message and set the loop to false?
you could write a function for that and just pass the array mon as a parameter

mybe this works too, not sure and cant test it atm.
if(mon1.alive ==mon2.alive == ... ==mon9.alive == false)
Last edited on
1
2
3
4
5
if( std::none_of(mon.begin(), mon.end(), std::mem_fn(&Monster::isAlive)) )
{
    std::cout << "Killed all Monster\n";
    loop=false;
}


oh, wait, you said it's an array..

1
2
3
4
5
if( std::none_of(mon, mon + 10, std::mem_fn(&Monster::isAlive)) )
{
    std::cout << "Killed all Monster\n";
    loop=false;
}


online demo: http://ideone.com/dtZJv5
Last edited on
1
2
3
4
5
6
if (!(mon[0].isAlive() || mon[1].isAlive() || mon[2].isAlive() || mon[3].isAlive() || mon[4].isAlive()
   || mon[5].isAlive() || mon[6].isAlive() || mon[7].isAlive() || mon[8].isAlive() || mon[9].isAlive() ))
        {
            cout << "Killed all Monster " << endl;
            loop = false;
        }
Couldn't you also do it like this:

1
2
3
4
5
if (!(mon[0].isAlive() && mon[1].isAlive() && mon[2].isAlive()  && mon[3].isAlive() && mon[4].isAlive() && mon[5].isAlive() && mon[6].isAlive() && mon[7].isAlive() && mon[8].isAlive() && mon[9].isAlive()))
		{
			cout << "Killed all Monster " << endl;
			loop = false;
		}


Ah no you can't. Soon as 1 monster died that would evaluate to true.
Last edited on
@ Raezzor Your version uses a ! operator outside the brackets, but you combine all the terms using &&. Mine is similar, but I use ||.

Which is right?
Both work and even my code works but I was just wondering if there is a shorter and more convenient way of doing this.
Yours is definitely better Chervil. :) Like I said, mine won't work properly since as soon as 1 monster died all the ands would evaluate to false, then the not would convert that to true, which is definitely not what is wanted here. Yours is much simpler and works as intended.
closed account (D80DSL3A)
Are you looking for something like this?
1
2
3
4
5
6
7
bool allDead = true;// presume true
for(int i=0; i <Nmonsters; ++i)
    if( mon[i].isAlive() )
    {
        allDead = false;
        break;
    }

If allDead is still true after that then they are all dead!

@cubbi: Your solution, while elegant, is probably incomprehensible to the OP.
Last edited on
do something like counter of killed monsters, every time when monster dies increase it.
Topic archived. No new replies allowed.