以下返回数字7.我的问题是我不完全确定为什么7是返回的数字。我尝试在调试模式下运行以将其分解但是 不幸的是,这没有帮助。
#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";
}
答案 0 :(得分:7)
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:
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
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
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