练习使用模板,自己编写《C++ Primer》上一道课后习题:
题目:编写一个函数模板,接受表示未知类型迭代器的一对值,找出在序列中出现得最频繁的值。
#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <algorithm>
#include <utility>
using namespace std;
template<typename T>
int Count(set< pair<T,int> > st,T val)
{
set< pair<T,int> >::iterator it = st.begin();
while (it != st.end())
{
if (*it->first == *val)
{
return 1;
}
++it;
}
return 0;
}
template<typename T>
set< pair<T,int> >::iterator Find(set< pair<T,int> > &st, const T& val)
{
set< pair<T,int> >::iterator it = st.begin();
while (it != st.end())
{
if (*it->first == *val)
{
return it;
}
++it;
}
return st.end();
}
template<typename T>
T frequent(T first,T end)
{
set< pair<T,int> > st;
while(first != end)
{
if (!Count(st,first))
{
int ct = 1;
pair<T,int> p(first,ct);
st.insert(p);
}
else
{
set< pair<T,int> >::iterator it = Find(st,first);
it->second += 1;
}
++first;
}
set< pair<T,int> >::iterator it1 = st.begin(),it2 = it1;
while(it1 != st.end())
{
if (it1->second > it2->second)
{
it2 = it1;
}
++it1;
}
return it2->first;
}
int main()
{
int a[] = {4,3,2,2,2,3,};
vector<int> vec(a,a+6);
vector<int>::iterator it = frequent(vec.begin(),vec.end());
cout << "数字出现最频繁的是: " << *it << endl;
string str[] = {"hello","world","world","love","love","love","you"};
vector<string> strval(str,str+7);
vector<string>::iterator st = frequent(strval.begin(),strval.end());
cout << "字符串出现最频繁的是: " << *st << endl;
return 0;
}