C++配列チェック


今日の授業で実験の授業で、一つの問題に出会って、1つの配列の中で最も出現回数の多い要素と回数を探して、そして出力する必要があります.初めてstructで辞書をシミュレートしたが,非常に面倒で複雑度はO(n*n)であった.実は、転化の思想を運用して、先にそれを並べ替えて、それから更に探すことができて、時間の複雑度の後でOだけあります(n*log_2(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

コード実装:アルゴリズムfindMax関数で実装
#include<iostream>
#include<string>
#include<algorithm> 
using namespace std;


template <class T>

void findMax(T* arr,int len){
    int j;  
    for(j=0;j<len;++j)
        cin>>arr[j];
    sort(arr,arr+len);
    int times=0 ,tem_times=1;
    T elem=arr[0] ;

    for(j = 1;j<len;++j)
        if(arr[j]==arr[j-1])
            tem_times++;
        else{
            if(tem_times>times){
                times = tem_times;
                elem = arr[j-1];
            }
            tem_times = 1;
        }
    if(tem_times>times){
        elem = arr[len-1];
        times = tem_times;
    }
    cout<<elem<<" "<<times<<endl;
}


int main(){
    int t,num;
    cin>>t;
    char type;
    while(t--){
        cin>>type;
        cin>>num;
        if(type=='I'){  
            int *arr = new int [num];
            findMax(arr,num);
        }
        else if(type=='S'){
            string *arr = new string [num];
            findMax(arr,num);
        }
        else if(type=='D'){
            double *arr = new double [num];
            findMax(arr,num);
        }
        else{
            char *arr = new char [num];
            findMax(arr,num);
        }

    }
    return 0;
}

本博文の関連内容をさらに交流することを歓迎します:ブログ園の住所:http://www.cnblogs.com/AsuraDong/CSDNアドレス:http://blog.csdn.net/asuradongコミュニケーションのために手紙を送ることもできます[email protected]転載を歓迎しますが、出典を教えてください:)