您的位置:首页 > 编程语言 > C语言/C++

C++[类设计] 一个使用new动态内存分配的集合类

2014-04-06 22:15 369 查看
定义并实现一个整数集合类int_set,集合类中cur_size表明当前集合中有几个整数,集合中最多含max_size个整数,存放集合元素的数组是动态的。要求提供的方法有:

(1)增加一个整数到集合中;

(2)从集合中去掉一个元素;

(3)判断一个元素是否在集合中;

(4)重载<<运算法,输入集合;重载>>运算符输出集合;

(5)分别实现集合的交、并、差运算。(未实现)

//in int_set.h
#ifndef _INT_SET_H_
#define _INT_SET_H_
#include <limits.h>
#include <iostream>
#define my_max_size INT_MAX
class int_set
{
private:
int * m_pInt;
public:
int cur_size;
public:
int_set();
bool AddEle(int Element);
bool IsInSet(int CheckEle);
bool RemoveEle(int RemElement);
int At(int index);
inline int * GetpInt() const {return m_pInt;}
void OutPut();
int_set & operator << (int element);
friend std::ostream & operator >> (std::ostream & os,const int_set & set);
~int_set();
};
#endif
//in int_set.cpp
#include "int_set.h"
#include <iostream>
int_set::int_set()
{
m_pInt=NULL;
cur_size=0;
}
bool int_set::AddEle(int Element)
{
if(cur_size==my_max_size)
return false;
int * pIntNew=new int[cur_size+1];
if(m_pInt != NULL)
{
/*int nErr=memcpy_s(pIntNew,sizeof(int)*(cur_size+1),m_pInt,sizeof(int)*(cur_size));
if(nErr !=0)
{
delete []pIntNew;
return false;
}*/
for(int i=0;i<cur_size;i++)
{
pIntNew[i]=m_pInt[i];
}
}
pIntNew[cur_size]=Element;
++cur_size;
delete []m_pInt;
m_pInt=pIntNew;

return true;
}
bool int_set::IsInSet(int CheckEle)
{
for(int i=0;i<cur_size;i++)
{
if(m_pInt[i]==CheckEle)
return true;
}
return false;
}
bool int_set::RemoveEle(int RemElement)
{
int *pIntNew=new int[cur_size-1];
static bool bIsInSet=false;

/*to find whether the RemElement is in the set or not,first.*/
for(int i=0;i<cur_size;i++)
{
if( !bIsInSet && (m_pInt[i]!=RemElement) )
{
pIntNew[i]=m_pInt[i];//not found,copy it directly.
}
else
{
pIntNew[i]=m_pInt[i+1];//or,skip it.
bIsInSet=true;
}
}

if(!bIsInSet)
{
delete []pIntNew;
return false;
}
else
{
--cur_size;
delete []m_pInt;
m_pInt=pIntNew;
return true;
}
}
int int_set::At(int index)
{
return m_pInt[index];//without checking boundary.
}
void int_set::OutPut()
{
for(int i=0;i<cur_size;i++)
std::cout << m_pInt[i] << "\t";
std::cout << std::endl;
}
int_set & int_set::operator << (int element)
{
this->AddEle(element);
return *this;
}
std::ostream & operator >> (std::ostream & os,const int_set & set)
{
//set.OutPut();Can not do this,because >> is not a member function.
for(int i=0;i<set.cur_size;i++)
std::cout << set.GetpInt()[i] << "\t";
std::cout << std::endl;
return os;
}
int_set::~int_set()
{
if(m_pInt != NULL)
delete []m_pInt;
}
//in main function
int main()
{
using std::cout;
using std::endl;
int_set MySet;
for(int i=0;i<9;i++)
//MySet.AddEle(i);//Ok
MySet<<i;
cout >> MySet;
//cout << "cur_size:" << MySet.cur_size << endl;
//MySet.RemoveEle(7);//OK
//MySet.OutPut();//OK
if(MySet.IsInSet(8))
cout << MySet.At(7) << endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐