C ++ count if function

Then the number 7 is returned. My problem is that im not quite sure why 7 is the return number. I tried working in debug mode to break it, but unfortunately this did not help.

#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
bool even_first( int x, int y ){
   if( (x % 2 == 0) && (y % 2 != 0) ) return true;
   if( (x % 2 != 0) && (y % 2 == 0) ) return false;
   return x < y;
}

struct BeforeValue {
    int bound;
    BeforeValue( int b ) : bound( b ) { }
    bool operator()( int value ) { return even_first( value, bound ); }
};


int main(){

list<int> my_list = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

int count = count_if( my_list.begin( ), my_list.end( ), BeforeValue( 5) );

cout << count << "\n";

}
+4
source share
1 answer

For a function, even_firstyou pass 2 parameters: the first parameter xis equal to the sequential values ​​of my_list, and the second parameter is yalways 5.

And in an even function we have 3 conditions:

  • if( (x % 2 == 0) && (y % 2 != 0) ) return true; y is 5, so y% 2! = 0 is always true x% 2 == 0 is true for: 0, 2, 4, 6, 8

  • if( (x % 2 != 0) && (y % 2 == 0) ) return false; It is always incorrect because y = 5, so y% 2 == 0 is false. Go to step 3

  • return x < y; We go to this statement only with the values: 1, 3, 5, 7, 9 and this is true for: 1 and 3

, even_first true : 0, 1, 2, 3, 4, 6, 8. 7

+7

All Articles