尽量减少代码量,
我要写一个查找图书的函数。她可以根据不同的方式查询(title_,author_,publishing_company_,number_都是string类型)
本来想用函数指针。
template<class InputIterator, class Predicate> InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred ) { for ( ; first!=last ; first++ ) if ( pred(*first) ) break; return first; }Find_title{public: Find_title(sting s1):s1_(s1){} bool operator()(const books& b) { return s1_==b.title_; }private: string s1_;};find_if(v.begin(),v.end(),ptr(s1));class Find_title{public: // 查找类型,也可用 enum 来定义 typedef int find_type; static const find_type title = 0; static const find_type author = title+1; static const find_type publishing_company = author+1; static const find_type number = publishing_company+1; Find_title(sting s1, find_type ft):s1_(s1), ft_(ft){} bool operator()(const books& b) { return s1_==get_value(b); }private: // 对于多个查找,switch总是不可避免的,如果不在这里,就是其他某个地方 const string& get_value(const books& b) const { switch(ft_) { case title: return b.title_; case author: return b.author_; case publishing_company: return b.publishing_company_; case number: return b.number_; }; return ""; // 或抛一个异常 }private: string s1_; find_type ft_;};做某项查找时,可以这样(如按 author_ 查找):find_if(v.begin(),v.end(),Find_title(s1, Find_title::author));