读书人

尽量减少代码量解决思路

发布时间: 2012-02-25 10:01:47 作者: rapoo

尽量减少代码量,
我要写一个查找图书的函数。她可以根据不同的方式查询(title_,author_,publishing_company_,number_都是string类型)

本来想用函数指针。

C/C++ code
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_if时,他的pred只接受单参数,也就是不能接受我传入的string(title_,author_,publishing_company_,number_)了
pred(vector<books> v,sting title_)这样的函数指针不能用于find_if


后来考虑用函数对象
C/C++ code
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));


为了减少代码量,我又想用模板,如find_if(v.begin(),v.end(),ptr<T>(s1));可是发现要是实现的话,必须替换b.title_(title_不是类型)。

用模板也解决的我的问题。用traits,不太熟...


[解决办法]
C/C++ code
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)); 

读书人网 >C++

热点推荐