2010-07-19 34 views
12

我使用STL函數count_if來計算雙精度元素中的所有正值 。例如我的代碼是一樣的東西:STL的標準謂詞count_if

vector<double> Array(1,1.0) 

Array.push_back(-1.0); 
Array.push_back(1.0); 

cout << count_if(Array.begin(), Array.end(), isPositive); 

其中函數isPositive被定義爲

bool isPositive(double x) 
{ 
    return (x>0); 
} 

下面的代碼將返回2.是否有這樣做上述 的方式沒有書面方式我自己的函數isPositive?我可以使用內置的 函數嗎?

謝謝!

+0

這裏有一個列表:http://msdn.microsoft.com/en-us /library/4y7z5x4b(v=VS.71).aspx – sje397 2010-07-19 16:41:56

回答

32

std::count_if(v.begin(), v.end(), std::bind1st(std::less<double>(), 0))是你想要的。

如果你已經using namespace std,更清晰的版本讀取

count_if(v.begin(), v.end(), bind1st(less<double>(), 0)); 

所有這些東西屬於<functional>頭,與其他標準的謂詞。

+9

或者你可以'bind2nd(更大的(),0)'。這是你的選擇! – 2010-07-19 16:26:40

+0

鑑於他已經'使用命名空間標準;'它會更清楚,沒有所有的'標準::'前綴。 – sje397 2010-07-19 16:45:07

+0

一個優雅的解決方案。如果我還需要計算所有非負值,該怎麼辦? – Wawel100 2010-07-19 17:00:47

1
cout<<std::count_if (Array.begin(),Array.end(),std::bind2nd (std::greater<double>(),0)) ; 
greater_equal<type>() -> if >= 0 
12

如果您正在使用MSVC++ 2010或GCC 4.5 +您可以使用真正 lambda函數編譯:

std::count_if(Array.begin(), Array.end(), [](double d) { return d > 0; });