|
|

楼主 |
发表于 2006-3-7 14:41:07
|
显示全部楼层
程序是这样的:这个程序是这样工作的:定义一个函数对象类IsAToothbrush,这个类的对象能判断出卖出的是否是牙刷 。如果这个记录是卖出牙刷的记录的话,函数调用operator()返回一个true,否则返回false。
- #include <iostream>
- #include <list>
- #include <bits/stl_list.h>
- #include <string>
- #include <algorithm>
- using namespace std;
- const string ToothbrushCode ("003");
- class IsAToothbrush //定义一个函数类对象。
- {
- public:
- bool operator () (string& SalesRecord )
- {
- return SalesRecord.substr(0,4) == ToothbrushCode;
- }
- };
- int main(void)
- {
- list<string> SalesRecords;
- SalesRecords.push_back("001, Soap");
- SalesRecords.push_back("002, Shampoo");
- SalesRecords.push_back("001, Toothbrush");
- SalesRecords.push_back("001, Tootthpaste");
- SalesRecords.push_back("001, Toothbrush");
- int NumberOfToothbrushes(0);
- count_if (SalesRecords.begin(), SalesRecords.end(), IsAToothbrush(), NumberOfToothbrushes);
- cout << "There were "<<NumberOfToothbrushes<<"toothbrushes sold " << endl;
- }
复制代码
用通用算法:count_If()时,编译出现这样的错误,是不是count_if()是Stl的新组件。
- [root@root STL]# g++ count_if.cpp -o count_if
- count_if.cpp: In function `int main()':
- count_if.cpp:32: error: no matching function for call to `count_if(std::_List_iterator<std::string>, std::_List_iterator<std::string>, IsAToothbrush, int&)'
- [root@root STL]#
复制代码 |
|