今天做书后面的习题的时候SB了~ 关键是以前学的不好,犯了低级错误,把new()当new[]使了, 一运行就报内存错误~~~后来google了一下,发现new[]时申请数组空间,而new()时对申请的变量空间初始化~~~
#include "10_9.h"
void IntSet::IntAND(const IntSet& set)
{
int *temp = new int[length>set.length ? length : set.length];
int i;
int j;
int k = -1;
for (i = 0; i < length; i++)
{
int self = data[i];
for (j = 0; j < set.length; j++)
{
if (self == set.data[j])
{
temp[++k] = data[i];
break;
}
}
}
length = k+1;
delete data;
data = NULL;
data = new int[length];
for (i = 0; i < length; i++)
{
data[i] = temp[i];
}
delete[] temp;
temp = NULL;
}
void IntSet::IntOR(const IntSet& set)
{
int *temp = new int[length +set.length];
int i;
int j;
int k ;
for (i = 0; i < length ; i++)
{
temp[i] = data[i];
}
k = length - 1;
for (i = 0; i< set.length; i++)
{
int s = set.data[i];
for (j = 0; j <= k; j++ )
{
if (s == temp[j])
{
break;
}
}
if (j > k)
{
temp[++k] = s;
}
}
length = k+1;
delete[] data;
data = NULL;
data = new int[length];
for (i = 0 ;i < length; i++)
{
data[i] = temp[i];
}
delete[] temp;
temp = NULL;
}
void IntSet::IntXOR(const IntSet& set)
{
int i;
int j;
int k = 0;
int len1;
int len2;
int *temp1 = new int[length];
int *temp2 = new int[set.length];
for (i = 0; i < length ; i++)
{
int s = data[i];
for (j = 0; j < set.length; j++)
{
if (s == set.data[j])
{
break;
}
}
if(j == set.length)
temp1[k++] = s;
}
len1 = k;
k = 0;
for (i = 0; i < set.length; i++)
{
int s = set.data[i];
for (j = 0; j < length; j++)
{
if (s == data[j])
{
break;
}
}
if(j == length)
temp2[k++] = s;
}
len2 = k;
delete[] data;
data = NULL;
length = len1 + len2;
data = new int[length];
for (i = 0; i < len1; i++)
{
data[i] = temp1[i];
}
for (i = 0; i < len2; i++)
{
data[i + len1] = temp2[i];
}
delete[] temp1;
temp1 = NULL;
delete[] temp2;
temp2 = NULL;
}
void IntSet::output()
{
int i;
cout<<"the element in this set is :"<<endl;
for (i = 0; i < length; i++)
{
cout<<data[i]<<' ';
}
cout<<endl;
}
void IntSet::init()
{
cout<<"please input "<<length<<" number"<<endl;
for (int i = 0; i < length ; i++)
{
cin>>data[i];
}
}
IntSet::IntSet(int len)
{
length = len;
data = new int[length];
}
IntSet::~IntSet()
{
if(data)
{
delete[] data;
data =NULL;
}
}
void main()
{
IntSet set1;
IntSet set2(6);
set1.init();
set2.init();
set1.output();
set2.output();
//set1.IntAND(set2);
//set1.IntOR(set2);
set1.IntXOR(set2);
set1.output();
}