2、元素计数算法
STL提供了两个计数功能的算法,分别是count(),以及条件计数的算法count_if();
【count()原型】
template <class InputIterator, class T>
typename iterator_traits<InputIterator>::difference_type
count (InputIterator first, InputIterator last, const T& val);
该函数模板行为等效于以下:
template <class InputIterator,class T>
typename iterator_traits<InputIterator>::difference_type
count(InputIterator first, InputIterator last, const T& val)
{
typename iterator_traits<InputIterator>::difference_type ret = 0;
while (first != last)
{
if (*first == val)
{
++ret;
++first;
}
}
return ret;
}
【count_if()原型】
template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);
template <class InputIterator, class UnaryPredicate>
typename iterator_traits<InputIterator>::difference_type
count_if(InputIterator first, InputIterator last, UnaryPredicate pred) //pred 为 true时,才统计元素个数,参数3应该是一个bool类型的函数对象
{
typename iterator_traits<InputIterator>::difference_type ret = 0;
while (first != last) {
if (pred(*first)) ++ret;
++first;
}
return ret;
}
示例一
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
// counting elements in array:
int myints[] = { 10,20,30,30,20,10,10,20 };
int mycount = std::count(myints, myints + 8 , 10);
std::cout << "10 appears " << mycount << " times.\n";
// counting elements in container:
std::vector<int> myvector(myints, myints + 8 );
mycount = std::count(myvector.begin(), myvector.end(), 20);
std::cout << "20 appears " << mycount << " times.\n";
return 0;
}
示例二
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
template<class T>
void init_value(T& vect, int first, int last)
{
if (last > first)
{
for (int i = first; i <= last; ++i)
{
vect.insert(vect.end(), i); //尾插
}
}
}
void Print(int elem)
{
cout << elem << " ";
}
bool pred(int elem)
{
return elem % 2 == 0; //是否是偶数
}
void main()
{
vector<int> myvector;
init_value(myvector, 1, 10);
for_each(myvector.begin(), myvector.end(), Print);
cout << endl;
int ct = count(myvector.begin(), myvector.end(), 4); //统计等于 4 的数的个数
int ct_if = count_if(myvector.begin(), myvector.end(), pred); //统计偶数的个数
int ct_if1 = count_if(myvector.begin(), myvector.end(), bind2nd(greater<int>(), 2)); //统计大于 2 的个数
cout << "ct " << ct << endl; // 1
cout << "ct_if " << ct_if << endl; // 5
cout << "ct_if1 " << ct_if1 << endl; 8
}
这里的bind2nd(greater<int>(), 2) 可以参考 C++11中的std::bind