设为首页 加入收藏

TOP

标准模板库(STL)学习指南之List容器(四)
2012-11-04 14:12:28 来源: 作者: 【 】 浏览:1531
Tags:标准 模板 STL 学习指南 List 容器
  用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

  用STL的通用算法count_if()来统计list中的元素个数

  count_if()是count()的一个更有趣的版本。他采用了STL的一个新组件,函数对象。count_if() 带一个函数对象的参数。函数对象是一个至少带有一个operator()方法的类。有些STL算法作为参数接收 函数对象并调用这个函数对象的operator()方法。

  函数对象被约定为STL算法调用operator时返回true或false。它们根据这个来判定这个函数。举个例子会 说的更清楚些。count_if()通过传递一个函数对象来作出比count()更加复杂的评估以确定一个对象是否应该被 记数。在这个例子里我们将数一数牙刷的销售数量。我们将提交包含四个字符的销售码和产品说明的销售记录。

/*
|| Using a function object to help count things
*/
#include <string>
#include <list>
#include <algorithm>

const string ToothbrushCode("0003");

class IsAToothbrush
{
 public:
  bool operator() ( string& SalesRecord )
  {
   return SalesRecord.substr(0,4)==ToothbrushCode;
  }
};

int main (void)
{
 list<string> SalesRecords;

 SalesRecords.push_back("0001 Soap");
 SalesRecords.push_back("0002 Shampoo");
 SalesRecords.push_back("0003 Toothbrush");
 SalesRecords.push_back("0004 Toothpaste");
 SalesRecords.push_back("0003 Toothbrush");

 int NumberOfToothbrushes(0);
 count_if (SalesRecords.begin(), SalesRecords.end(),
 IsAToothbrush(), NumberOfToothbrushes);

 cout << "There were "
 << NumberOfToothbrushes
 << " toothbrushes sold" << endl;
}

  这是这个程序的输出:

  There were 2 toothbrushes sold 这个程序是这样工作的:定义一个函数对象类IsAToothbrush,这个类的对象能判断出卖出的是否是牙刷 。如果这个记录是卖出牙刷的记录的话,函数调用operator()返回一个true,否则返回false。

  count_if()算法由第一和第二两个iterator参数指出的范围来处理容器对象。它将对每个 IsAToothbrush()返回true的容器中的对象增加NumberOfToothbrushes的值。

  最后的结果是NumberOfToothbrushes这个变量保存了产品代码域为"0003"的记录的个数,也就是牙刷的个数。

  注意count_if()的第三个参数IsAToothbrush(),它是由它的构造函数临时构造的一个对象。你可以把IsAToothbrush类的一个临时对象 传递给count_if()函数。count_if()将对该容器的每个对象调用这个函数。
首页 上一页 1 2 3 4 5 6 7 下一页 尾页 4/7/7
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇MFC程序员的WTL指南之对话框与控.. 下一篇用VC实现将自绘图形输出为bmp文件

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: