标准模板库(STL)List介绍(六)

2011-06-07 12:31:23 · 作者: · 浏览: 9211
 
  
用STL的通用算法count()来统计list中的元素个数。 
      STL的通用算法count()和count_it()用来给容器中的对象记数。就象for_each()一样,count()和count_if() 算法也是在iterator范围内来做的。  
  
     让我们在一个学生测验成绩的list中来数一数满分的个数。这是一个整型的List。  
  
  /* 
|| How to count objects in an STL list 
*/ 
#include <list> 
#include <algorithm> 
int main (void)  
   list<int> Scores; 
   Scores.push_back(100); Scores.push_back(80); 
   Scores.push_back(45); Scores.push_back(75); 
   Scores.push_back(99); Scores.push_back(100); 
   int NumberOf100Scores(0);      
   count (Scores.begin(), Scores.end(), 100, NumberOf100Scores); 
   cout << "There were " << NumberOf100Scores << " scores of 100" << endl; 
     count()算法统计等于某个值的对象的个数。上面的例子它检查list中的每个整型对象是不是100。每次容器中的对象等于100,它就给NumberOf100Scores加1。这是程序的输出:  
  
   There were 2 scores of 100