Dec 5, 2012 at 4:42pm UTC
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 Dec 5, 2012 at 4:44pm UTC
Dec 5, 2012 at 4:47pm UTC
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 Dec 5, 2012 at 4:49pm UTC
Dec 5, 2012 at 5:48pm UTC
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 Dec 5, 2012 at 5:50pm UTC
Dec 5, 2012 at 5:54pm UTC
@ 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?
Dec 5, 2012 at 5:58pm UTC
Both work and even my code works but I was just wondering if there is a shorter and more convenient way of doing this.
Dec 5, 2012 at 6:06pm UTC
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.
Dec 5, 2012 at 8:48pm UTC
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 Dec 5, 2012 at 8:51pm UTC
Dec 6, 2012 at 10:20am UTC
do something like counter of killed monsters, every time when monster dies increase it.