原文位址:http://www.cplusplus.com/reference/algorithm/count_if/
function template <algorithm>
std::count_if
template <class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
Return number of elements in range satisfying condition Returns the number of elements in the range
[first,last)
for which pred is true.
傳回範圍内對每個元素調用pred傳回true的次數。 例子:
#include <iostream>
#include <algorithm>
#include <vector>
#include <array>
using namespace std;
bool ismod2(int i){
return i%2==0;
}
void countif(){
vector<int> vi{1,5,7,8,9,9,8,5,9};
array<int,7> ai{888,666,555,222,111,555,777};
cout<<"vi=";
for(int &i:vi)
cout<<i<<" ";
cout<<endl;
int cv=count_if(vi.begin(),vi.end(),ismod2);
cout<<"能被2整除的一共有"<<cv<<"個"<<endl;
cout<<"ai=";
for(int &i:ai)
cout<<i<<" ";
cout<<endl;
int ca=count_if(ai.begin(),ai.end(),[](int i){return i>500;});
cout<<"大于500的一共有"<<ca<<"個"<<endl;
}
運作截圖:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9UFVOhXSU5keRRkT0UEWjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zN1UzMzUzMwETMxkDM0EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
The behavior of this function template is equivalent to:
| |
Parameters
- first, last
- Input iterators to the initial and final positions of the sequence of elements. The range used is
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.
元素的範圍。
pred - Unary function that accepts an element in the range as argument, and returns a value convertible to
bool
. The value returned indicates whether the element is counted by this function.
The function shall not modify its argument.
This can either be a function pointer or a function object.
接受一個元素作為參數兵傳回一個bool值的一進制函數。
Return value
The number of elements in the range
[first,last)
for which pred does not return
false
.
The return type (iterator_traits<InputIterator>::difference_type) is a signed integral type.
傳回範圍内對每個元素調用pred傳回true的次數。
Example
| | Edit & Run |
Output:
|
Complexity
Linear in the distance between first and last: Calls pred once for each element.
Data races
The objects in the range
[first,last)
are accessed (each object is accessed exactly once).
Exceptions
Throws if pred trhows or if any of the operations on iterators throws.
Note that invalid arguments cause undefined behavior.
——————————————————————————————————————————————————————————————————
//寫的錯誤或者不好的地方請多多指導,可以在下面留言或者點選左上方郵件位址給我發郵件,指出我的錯誤以及不足,以便我修改,更好的分享給大家,謝謝。
轉載請注明出處:http://blog.csdn.net/qq844352155
author:天下無雙
Email:[email protected]
2014-9-11
于GDUT
——————————————————————————————————————————————————————————————————