设为首页 加入收藏

TOP

标准模板库(STL)List介绍(九)
2011-06-07 12:31:23 来源: 作者: 【 】 浏览:9182
Tags:标准 模板 STL List 介绍
 
  
使用count_if()的一个更加复杂的函数对象。 
     我们可以更进一步的研究一下函数对象。假设我们需要传递更多的信息给一个函数对象。我们不能通过 调用operator来作到这点,因为必须定义为一个list的中的对象的类型。 然而我们通过为IsAToothbrush指出一个非缺省的构造函数就可以用任何我们所需要的信息来初始化它了。 例如,我们可能需要每个牙刷有一个不定的代码。我们可以把这个信息加到下面的函数对象中:  
  
   
/* 
|| Using a more complex function object 
*/ 
#include <iostream.h> 
#include <string> 
#include <list> 
#include <algorithm> 
  
class IsAToothbrush  
public: 
   IsAToothbrush(string& InToothbrushCode) :  
       ToothbrushCode(InToothbrushCode) {} 
   bool operator() (string& SalesRecord)  
   { 
     return SalesRecord.substr(0,4)==ToothbrushCode; 
   }        
private: 
   string 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"); 
    
   string VariableToothbrushCode("0003"); 
  
   int NumberOfToothbrushes(0);   
   count_if (SalesRecords.begin(), SalesRecords.end(),  
               IsAToothbrush(VariableToothbrushCode), 
                  NumberOfToothbrushes); 
   cout << "There were  " 
        << NumberOfToothbrushes  
        << " toothbrushes matching code " 
        << VariableToothbrushCode 
        << " sold"  
        << endl; 
程序的输出是:  
  
There were  2 toothbrushes matching code 0003 sold 
     这个例子演示了如何向函数对象传递信息。你可以定义任意你想要的构造函数,你可以再函数对象中做任何你 想做的处理,都可以合法编译通过。  
  
     你可以看到函数对象真的扩展了基本记数算法。 
  
首页 上一页 6 7 8 9 10 11 12 下一页 尾页 9/18/18
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇 C++语言的url encode 和decode 下一篇C++ map的基本操作和使用

评论

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