2015年10月5日月曜日

STLのcountを使う(C++)

STLのcount

STLのalgorithmライブラリに含まれるcountはIteratableなオブジェクトに現れる要素の個数を数えるだけのアルゴリズムです。

定義は
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;
}
となっています。 簡単なアルゴリズムですが要素を数える必要がある場合は使っても良いかもしれません。

使用例:
#include <iostream>
#include <ctime>
#include <vector>
#include <algorithm>

using namespace std;
/* rand() による乱数をカウントする */
void randomTest(const size_t size, const size_t max) {

  vector<int> vec;
  srand((unsigned int)time(NULL));

  for(int i = 0; i < size; i++) {
    vec.push_back(rand() % max);
  }

  for(int i = 0; i < max; i++) {
    const int cnt = count(vec.begin(), vec.end(), i);
    cout << i << "は" << cnt << "個あります" << endl;
  }

}

int main() {

  size_t size = 10000;
  size_t max = 10;

  randomTest(size, max);

  return 0;
}

結果:

0は1021個あります
1は979個あります
2は1016個あります
3は974個あります
4は1013個あります
5は965個あります
6は1025個あります
7は1005個あります
8は1004個あります
9は998個あります

0 件のコメント:

コメントを投稿