64,282
社区成员
发帖
与我相关
我的任务
分享
/*File:mset.h声明一个M_Set类*/
#include <iostream>
using namespace std;
class M_Set
{
public:
M_Set(int sz);
void Insert(const int& x);
int IsEmpty();
int IsFull();
int Minvalue();
void DeleteMin();
friend ostream& operator <<(ostream& out,const M_Set& mset)
{
for(int i=0;i <mset.num;i++)
out <<mset.elem[i] <<" ";
return out;
}
private:
int* elem;
int maxsize,num;
int FindMin();
};
/*File mset.cpp 类M_Set的实现*/
#include <assert.h>
#include "mset.h"
M_Set::M_Set(int sz):num(0)
{
if(sz>0)
{
maxsize = sz;
elem = new int[maxsize];
}
else
cerr <<"the length if SET is error!" <<endl;
}
int M_Set::IsEmpty()
{
if(num==0) return 1;
return 0;
}
int M_Set::IsFull()
{
if(num==maxsize) return 1;
return 0;
}
int M_Set::Minvalue()
{
return elem[FindMin()];
}
void M_Set::Insert(const int& x)
{
assert(!IsFull());
elem[num++]=x;
}
void M_Set::DeleteMin()
{
int loc=FindMin();
for(int i=loc;i <num;i++) elem[i]=elem[i+1];
num--;
}
/*File: msetapp.cpp */
#include <iostream>
#include "mset.h"
using namespace std;
void fun(int* A,M_Set& M,int n,int k)
{
for(int i=0;i <k;i++) M.Insert(A[i]);
for(i=k;i <n;i++)
if(A[i]>M.Minvalue())
{
M.DeleteMin();
M.Insert(A[i]);
}
}
void main()
{
const int MAX=20;
int X[MAX],k,n;
cout <<"input n";
cin>>n;
cout <<"input k";
cin>>k;
if(k>n)
{
cout <<"error!\n";
exit(1);
}
cout <<"input the random start:";
unsigned seed;
cin>>seed;
srand(seed);
for(int i=0;i <n;i++)
X[i]=rand()%1000;
for(int j=0;j <n;i++)
cout <<X[j] <<" ";
cout <<'\n';
M_Set Y(k);
fun(X,Y,n,k);
cout <<"the result is:" <<endl;
cout <<Y <<endl;
}