#include <iostream>using namespacestd;template<classT>classctopk{ Public: CTOPK (); ~CTOPK (); T*m_data; intGETTOPK (Const Char* SFile,int&nTop);Private: voidClear (); voidHeapadjust (intNstart,intNlen); voidBuildheap (intnlen);}; Template<classT>CTOPK<T>:: Ctopk () {m_data=NULL;} Template<classT>CTOPK<t>::~ctopk () {Clear ();} Template<classT>voidCtopk<t>:: Clear () {if(NULL! =m_data) { Delete[] m_data; M_data=NULL; }}//get the number of K in front toptemplate<classT>intCTOPK<T>::GETTOPK (Const Char* SFile,int&NTop) {FILE* fp =NULL; T FData; inti =0; //Judging input Parameters if((NULL = = SFile) | | (NTop <=0) ) {cout<<"Error parameter"<<Endl; return-1; } //Clear OperationClear (); //Open Filefp = fopen (SFile,"R"); if(NULL = =FP) {cout<<"Open File failed!"<<Endl; return-1; } //Allocate SpaceM_data =NewT[ntop]; if(NULL = =m_data) {cout<<"new operator failed!"<<Endl; return-1; } cout<<"Please wait ..."<<Endl; //ntop data before reading, note the type of data T for(i =0; i < NTop; i++) { if(EOF! = fscanf (FP,"%d", &fData)) {M_data[i]=FData; } Else { Break; } } //the largest number is less than ntop, the first I data if(I <NTop) {NTop=i; } Else{buildheap (NTOP);//build a small top pile while(EOF! = fscanf (FP,"%d", &fData)) { if(FData > m_data[0]) { //Swap and adjust the heapm_data[0] =FData; Heapadjust (0, NTop); } } } return 0;}//Adjust small Gan, top K minimum for heap topstemplate<classT>voidCtopk<t>::heapadjust (intNstart,intNlen) { intNminchild =0; T ftemp; while( (2* Nstart +1) <Nlen) {Nminchild=2* Nstart +1; if( (2* Nstart +2) <Nlen) { //Compare Saozi right subtree, record index of minimum value if(m_data[2* Nstart +2] < m_data[2* Nstart +1]) {Nminchild=2* Nstart +2; } } //Change Data if(M_data[nstart] >M_data[nminchild]) { //exchanging data for Nstart and NmaxchildFtemp =M_data[nstart]; M_data[nstart]=M_data[nminchild]; M_data[nminchild]=ftemp; //the heap is destroyed and needs to be re-adjustedNstart =Nminchild; } Else { //compare left and right children are large heap is not destroyed, no longer need to adjust Break; } }}//Build Heaptemplate<classT>voidCtopk<t>::buildheap (intNlen) { inti =0; T ntemp; //will M_data[0, Len-1] built small Gan, here only maintain a small Gan, not sorted for(i = nlen/2-1; I >=0; i--) {heapadjust (I, Nlen); }}intMainintargcChar*argv[]) { Charszfile[ -] = {0}; intNnum =0; CTOPK<int>objtopsum; cout<<"Please input count file name:"<<Endl; CIN>>Szfile; cout<<"Please input top num:"<<Endl; CIN>>Nnum; OBJTOPSUM.GETTOPK (Szfile, nnum); intFsum =0; for(inti =0; i < Nnum; i++) {cout<<objTopSum.m_Data[i]<<" "; Fsum+=Objtopsum.m_data[i]; } cout<<"\ntop"<< Nnum <<"value ="<< Fsum <<Endl; return 0;}
Max K number, and class template