پیاده سازی آرایه پویا با کلاس
سه شنبه, ۲ خرداد ۱۳۹۶، ۰۷:۲۰ ب.ظ
#include "stdafx.h"
#include <iostream>
using namespace std;
class Array{
int cap;
int len;
int *arr;
public:
Array() //constructor
{
cap=0;
len=0;
arr=new int;
}
Array(int x) //constructor
{
cap=x;
len=0;
arr=new int[x];
}
Array(const Array &temp) //copy constructor
{
cap=temp.cap;
len=temp.len;
arr=new int[cap];
for(int i=0;i<temp.len;i++)
arr[i]=temp.arr[i];
}
~Array() //destructor
{
delete [] arr;
}
void set(int x)
{
if(len<cap)
{
arr[len]=x;
len++;
}
else
{
int *temp=new int[cap]; //new array
for(int i=0;i<cap;i++) //set member of arr to new array named temp
temp[i]=arr[i];
delete [] arr; //delete arr
int *arr=new int[cap*2]; //new arr with more capacity
for(int i=0;i<cap;i++) //get back member of old arr to new arr with temp
arr[i]=temp[i];
delete [] temp; //free space of temp with delet that
cap*=2; //more cap (mean : cap=cap*2)
arr[len]=x; //set
len++;
}
}
void print()
{
for(int i=0;i<len;i++)
cout<<arr[i]<<endl;
}
Array& operator =(Array temp)
{
if(cap<=temp.cap)
{
for(int i=0;i<temp.len;i++)
arr[i]=temp.arr[i];
len=temp.len;
cap=temp.cap;
}
else
{
delete [] arr;
int *arr=new int[temp.cap]; //fix array capacity
for(int i=0;i<temp.len;i++) //put member
arr[i]=temp.arr[i];
len=temp.len;
cap=temp.cap;
}
return *this;
}
Array operator +(Array A2)
{
Array A3(cap+A2.cap);
A3.cap=cap+A2.cap;
A3.len=len+A2.len;
for(int i=0;i<len;i++)
A3.arr[i]=arr[i];
for(int i=len;i<A2.len;i++)
A3.arr[i]=A2.arr[i];
return A3;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Array A(5);
A.set(0);A.set(1);A.set(2);
Array B(5);
A.set(4);A.set(5);
Array C;
C=A+B;
C.print();
system("pause");
return 0;
}
- ۹۶/۰۳/۰۲