count_if

[機能]

  指定した範囲で,単項関数オブジェクトが真となる要素の数を返します.

[形式]
	#include <algorithm>
	#include <functional>

	template <class InputIterator, class Predicate> size_t count_if(InputIterator first, InputIterator last, UnaryPredicate pred);
		

[使用例]

  1. 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
    			
[参照]

count

ホームページ 目次 演習解答例目次 付録目次 索引