count と count_if の使用方法です.
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
// 奇数の判定
class is_odd : public unary_function<int, bool>
{
public:
result_type operator() (argument_type k)
{
return (result_type)(k % 2);
}
};
int main()
{
int n;
vector<int> v;
vector<int>::iterator it;
// 初期設定
printf("**初期状態**\n");
v.push_back(4);
v.push_back(1);
v.push_back(4);
v.push_back(3);
v.push_back(4);
for (it = v.begin(); it != v.end(); it++)
printf(" %d", *it);
printf("\n");
// 4 である要素の数
n = count(v.begin(), v.end(), 4);
printf("4 である要素数: %d\n", n);
// 奇数である要素の数
n = count_if(v.begin(), v.end(), is_odd());
printf("奇数の要素数: %d\n", n);
return 0;
}
(出力)
**初期状態**
4 1 4 3 4
4 である要素数: 3
奇数の要素数: 2