Loading [MathJax]/extensions/tex2jax.js

2015年10月5日月曜日

STLのcountを使う(C++)

STLのcount

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

定義は
  1. template <class InputIterator, class T>  
  2.   typename iterator_traits<InputIterator>::difference_type  
  3.     count (InputIterator first, InputIterator last, const T& val)  
  4. {  
  5.   typename iterator_traits<InputIterator>::difference_type ret = 0;  
  6.   while (first!=last) {  
  7.     if (*first == val) ++ret;  
  8.     ++first;  
  9.   }  
  10.   return ret;  
  11. }  
となっています。 簡単なアルゴリズムですが要素を数える必要がある場合は使っても良いかもしれません。

使用例:
  1. #include <iostream>  
  2. #include <ctime>  
  3. #include <vector>  
  4. #include <algorithm>  
  5.   
  6. using namespace std;  
  7. /* rand() による乱数をカウントする */  
  8. void randomTest(const size_t size, const size_t max) {  
  9.   
  10.   vector<int> vec;  
  11.   srand((unsigned int)time(NULL));  
  12.   
  13.   for(int i = 0; i < size; i++) {  
  14.     vec.push_back(rand() % max);  
  15.   }  
  16.   
  17.   for(int i = 0; i < max; i++) {  
  18.     const int cnt = count(vec.begin(), vec.end(), i);  
  19.     cout << i << "は" << cnt << "個あります" << endl;  
  20.   }  
  21.   
  22. }  
  23.   
  24. int main() {  
  25.   
  26.   size_t size = 10000;  
  27.   size_t max = 10;  
  28.   
  29.   randomTest(size, max);  
  30.   
  31.   return 0;  
  32. }  

結果:

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

Pythonで地図空間データを扱う⑤

ベースの地図が出来た所で、他のデータを被せてみます。 国土地理院の  500mメッシュ別将来推計人口データ  を使用します。 同じく神奈川県のデータ  500m_mesh_suikei_2018_shape_14.zip をダウンロードします。 ベースの地図データと同じ場所に展開...