题目描述
某小镇要票选镇长,得票最高者当选。但由于投票机制不健全,导致每届投票时,候选人在投票系统的识别码类型不一致。请编写函数模板,能针对多种类型的数据,查找出得票最高的元素。其中,每届投票的选票有n张,识别码类型为T
注意:必须使用模板函数
输入
第一行输入t表示有t个测试实例
第二行先输入一个大写字母表示识别码类型,I表示整数类型,C表示字符型,S表示字符串型;然后输入n表示数组长度。
第三行输入n个数据
依次输入t个实例
输出
每行输出一个结果,分别输出当选者的识别码和得票数,以空格分开。
3
I 10
5 3 5 2 9 7 3 7 2 3
C 8
a b a e b e e q
S 5
sandy david eason cindy cindy
样例输出
3 3
e 3
cindy 2
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
template <class T>
void Find(T* arr,int len)
{
int i, num = 0 ,count = 1;
for(i = 0; i < len; i++)
cin >> arr[i];
sort(arr, arr+len);
T symbol = arr[0];
for(i = 1; i < len; i++)
{
if(arr[i] == arr[i-1])
count++;
else
{
if(count>num)
{
num = count;
symbol = arr[i-1];
}
count = 1;
}
}
if(count>num)
{
symbol = arr[len-1];
num = count;
}
cout<<symbol<<" "<<num<<endl;
}
int main()
{
int t,num;
cin >> t;
char type;
while(t--)
{
cin>>type;
cin>>num;
if(type=='I')
{
int *arr = new int [num];
Find(arr,num);
}
else if(type=='S')
{
string *arr = new string [num];
Find(arr,num);
}
else if(type=='D')
{
double *arr = new double [num];
Find(arr,num);
}
else
{
char *arr = new char [num];
Find(arr,num);
}
}
return 0;
}