2013-06-13 132 views
0

我有这个类。重构代码重复

void QueryStatistics::increase_freq_title (std::string & title) 
{ 
    for (unsigned int i=0; i < queries_title.size(); i++) 
    { 
     if (queries_title[i].first == title) 
     { 
      queries_title[i].second += 1; 
      return; 
     } 
    } 
} 

我该如何重构这个以避免不得不重复相同的代码四次?

+0

你为什么不建立一个功能,并添加参数,需要一个载体? – OGH

+0

使用'template void increase_freq(std :: vector >&v,T const&k)',''''''就像'样本代码'在'queries_title'上执行操作。我会让它成为一个免费的功能。 – Yakk

回答

1

我认为这会做到这一点,如果使自己的模板是一个选项。

template<typename T, typename U> 
void QueryStatistics::increase_freq (T title, std::vector<U>& vec) 
{ 
    for (unsigned int i=0; i < vec.size(); i++) 
    { 
     if (vec[i].first == title) 
     { 
      vec[i].second += 1; 
      return; 
     } 
    } 
} 

由于您的载体是私人的,你可以有你的四个众成员函数调用上面,而不是重复相同的代码的功能。

0

其实,无需复杂的模板参数,只是简单的

#include <string> 
    #include <vector> 

    class QueryStatistics 
    { 
     private: 
      std::vector < std::pair <std::string,int > > queries_title; 
      std::vector < std::pair <std::string,int > > queries_author; 
      std::vector < std::pair <std::string,int > > queries_phrase; 
      std::vector < std::pair <int,int > >  queries_id; 

     public: 

      template<typename T, typename U> 
      void increase(T& query, U const& para) 
      { 
       for (unsigned int i=0; i < query.size(); i++) 
       { 
        if (query[i].first == para) 
        { 
         query[i].second += 1; 
         return; 
        } 
      } 


      } 

      void increase_freq_title (std::string & title) 
      { 
       increase(queries_title,title); 

      } 
      void increase_freq_author (std::string & author) 
      { 
        increase(queries_author,author); 
      } 
      void increase_freq_phrase (std::string & phrase) 
      { 
       increase(queries_phrase,phrase); 
      } 
      void increase_freq_id  (int id_doc) 
      { 
       increase(queries_id,id_doc); 
      } 
    };