STL 算法问题

来源:百度知道 编辑:UC知道 时间:2024/06/18 01:27:53
const string ToothbrushCode("0003");

class IsAToothbrush
{
public:
bool operator() ( string& SalesRecord )
{
return SalesRecord.substr(0,4)==ToothbrushCode;
}
};
建立的这个类有什么用啊? bool operator() ( string& SalesRecord ) 这句话有什么用?
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;
}

IsAToothbrush 是函数对象(function object),如果可以,关于这个概念还是建议你翻一下手头的书,你就明白了。函数对象的定义就是一个类重载了()运算符,而函数count_if 需要一个函数对象(我对stl也不完全了解,不知道这里传一个函数指针是不是也是可以的,但是例子里面用的是函数对象),这个对象的作用就是 count_if函数执行的时候,会遍历集合的元素,用调用operator()来判断是否要删除某个元素