ゲームが作れるようになるまでがんばる日記

ゲーム制作のことを中心にゲームに関することを書いています

カウントアルゴリズム

STLアルゴリズムの中からカウントアルゴリズムを試してみた。

size_t count(start, end, val);
size_t count_if(start, end, func);

count()はstartからendの中に指定した値のものの個数を返す。count_if()はfuncで指定した関数がtrueを返すものの個数を返す。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 10000超えてるなら真を返す関数
bool isover(int n)
{
    return (n>10000) ? true : false;
}

int main()
{
    vector<int> v;

    // 整数をランダムに10個
    for(int i=0; i<10; i++) v.push_back(rand());
    vector<int>::iterator p = v.begin();
    while( p != v.end() ) {
        cout << *p << " ";
        ++p;
    }
    cout << endl;

    int n;
    // 1000の個数をカウント
    n = count(v.begin(), v.end(), 1000);
    cout << n << endl;

    // 10000を超えているものの個数をカウント
    n = count_if(v.begin(), v.end(), isover);
    cout << n << endl;
}

実行結果
41 18467 6334 26500 19169 15724 11478 29358 26962 24464
0
8