[英]Counting elements greater than a number in vector
我想計算c ++向量中大於數字的元素數。 閾值將從用戶輸入。
計算大於數字的元素的代碼如下:
ctr=count_if(v.begin(),v.end(), greater1);
相應的功能:
bool greater1(int value)
{
return value >= 8;
}
問題是我只知道在count_if
函數調用之前的閾值(這里是8),所以我需要將閾值t
作為參數傳遞。 如何建立相同?
NB僅適用於c ++ 11標准
最簡單的方法是使用lambda表達式 。 使用它可以在count_if
的調用站點中構建一個仿函數(稱為Closure對象),然后您可以在lambda體內使用您所知道的。 這會讓你有類似的東西
auto minimum_value = /* something that gets the minimum value you want to use for the comparison */
auto count = std::count_if(v.begin(), v.end(),[&](auto const& val){ return val >= minimum_value; });
// ^ use this to capture a reference of minimum_value
創建一個為您提供閾值功能的功能!
auto above(int threshold) {
// This captures a copy of threshold
return [=](int value) {
return value >= threshold;
};
};
然后,您可以使用above
的計數來獲取計數,只需將閾值作為參數傳遞:
auto count = count_if(v.begin(), v.end(), above(8));
就像NathanOliver所說 ,我們需要“捕獲”內部使用的閾值。 一個lambda完成了,但是怎么樣?
當你寫一個lambda像
int threshold = 8;
std::count_if(/*...*/, [threshold](int next_val){return next_val >= threshold;});
在C ++ 11及更高版本中,編譯器使用這個lambda語法生成一個輕量級類,公開函數調用操作符,如下所示:
struct my_greater_equal
{
explicit my_greater_equal(int _threshold) : threshold(_threshold){}
bool operator()(int next_val) const
{
return next_val >= threshold;
}
int threshold;
};
(這幾乎就像lambda的樣子)
然后創建一個實例並在count_if
as-if:
std::count_if(my_collection.cbegin(), my_collection.cend(), my_greater_equal{8});
在內部, std::count_if
為集合中的每個元素調用my_greater_equal::operator()
。
Pre-C ++ 11我們必須手動創建這些輕量級函數對象 (有時稱為仿函數,即使這在技術上並不正確)
事情現在變得容易多了:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.