Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ count if function

Tags:

c++

The following returns the number 7. My problem is that im not exactly sure why 7 is the number returned. I tried running in in debug mode to break it down but unfortunately that 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";

}
like image 323
Vermonster Avatar asked Mar 16 '23 04:03

Vermonster


1 Answers

To function even_first you pass 2 parameters: first parameter x is equal to successive values from my_list and the second parameter y is always 5.

And in the even_first function we have 3 conditions:

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

  2. if( (x % 2 != 0) && (y % 2 == 0) ) return false; It is always false because y = 5 so y % 2 == 0 is false. We go to point 3

  3. return x < y; To this statement we go only with values: 1, 3, 5, 7, 9 and it is true for: 1 and 3

So finally the even_first returns true for: 0, 1, 2, 3, 4, 6, 8. And the size of this set is 7

like image 85
AdamF Avatar answered Mar 28 '23 07:03

AdamF