Page List

Search on the blog

2011年4月25日月曜日

知ってると便利なSTL(6) count

STL勉強シリーズ6回目。
今回はcountについて。その名の通り、コンテナに格納されている特定の要素の数を数えます。

使い方としては、以下の3つくらいでしょうか。
  1. ベクトルの中に、目的の要素はいくつあるか数える
  2. 文字列の中に、目的の文字はいくつあるか数える
  3. 配列の中に、目的の要素はいくつあるか数える
それぞれ、サンプルソースを載せておきます。

  1. int main () {  
  2.     vector<int> nums;  
  3.   
  4.     for (int i = 0; i < 100; i++)  
  5.         nums.push_back(rand()%10);  
  6.   
  7.     for (int i = 0; i < 10; i++)  
  8.         cout << count(nums.begin(), nums.end(), i) << endl;  
  9.   
  10.     return 0;  
  11. }  



  1. int main () {  
  2.     string name = "tanaka tarou";  
  3.   
  4.     cout << count(name.begin(), name.end(), 'a') << endl;  
  5.   
  6.     return 0;  
  7. }  



  1. int main () {  
  2.     double x[] = {0.0, 0.1, 0.14, 0.0, 0.3, 0.6};  
  3.     int sz = sizeof(x) / sizeof(double);  
  4.   
  5.     cout << count(x, x+sz, 0.0) << endl;  
  6.   
  7.     return 0;  
  8. }  

0 件のコメント:

コメントを投稿