我上过这堂课:
#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:
QueryStatistics();
virtual ~QueryStatistics();
void increase_freq_title (std::string & title);
void increase_freq_author (std::string & author);
void increase_freq_phrase (std::string & phrase);
void increase_freq_id (int id_doc);
};
这段代码重新放了4次,但每次都有不同的向量。
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 :(得分: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;
}
}
}
由于你的向量是私有的,你可以让你的四个公共成员函数调用上面的函数而不是重复相同的代码。
答案 1 :(得分: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);
}
};