2013-06-13 128 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); 
      } 
    };