语法:
#include <algorithm>
//1)
count( InputItIterator first, InputItIterator last, const T &value );
//2)
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
(1) 计数等于 value 的元素。
(2)按条件统计元素个数,返回范围内满足条件的元素数,(即计数谓词 pred 对其返回 true 的元素)。
参数:
first,last | 要检验的元素范围,代表迭代器的初始和最终位置。使用的范围是[first,last) ,它包含first和last之间的所有元素,包括first指向的元素,但不包含last指向的元素。 |
value | 要搜索的值 |
pred | 一元谓词。接受范围内的元素作为参数,并返回bool类型的值 。返回的值表示函数是否对此元素进行计数。该功能不得修改其参数。这可以是一个函数指针或一个函数对象。 |
此函数模板的行为等效于:
①count():
template <class InputItIterator, class T>
typename iterator_traits<InputIt>::difference_type
count(InputItIterator first, InputItIterator last, const T &value)
{
typename iterator_traits<InputIt>::difference_type ret = 0;
for (; first != last; ++first)
{
if (*first == value)
{
ret++;
}
}
return ret;
}
②count_if():
template <class InputItIterator, class UnaryPredicate>
typename iterator_traits<InputIt>::difference_type
count_if(InputItIterator first, InputItIterator last, UnaryPredicate p)
{
typename iterator_traits<InputIt>::difference_type ret = 0;
for (; first != last; ++first)
{
if (p(*first))
{
ret++;
}
}
return ret;
}
示例:
①count():
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// counting elements in array:
int myints[] = {10, 20, 30, 30, 20, 10, 10, 20}; // 8 elements
int mycount = count(myints, myints + 8, 10);
cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
vector<int> myvector(myints, myints + 8);
mycount = std::count(myvector.begin(), myvector.end(), 20);
cout << "20 appears " << mycount << " times.\n";
system("pause");
return 0;
}
/*输出
10 appears 3 times.
20 appears 3 times.
*/
②count_if():
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
bool IsOdd(int i)
{
return i % 2 == 1;
}
int main()
{
vector<int> myvector;
for (int i = 1; i < 10; i++)
myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9
int mycount = count_if(myvector.begin(), myvector.end(), IsOdd);
cout << "myvector contains " << mycount << " odd values.\n";
mycount = count_if(myvector.begin(), myvector.end(), [](int i) { return i % 3 == 0; });
cout << "myvector contains " << mycount << " Number divided by 3.\n";
system("pause");
return 0;
}
/*输出
myvector contains 5 odd values.
myvector contains 3 Number divided by 3.
*/