Schreibe eine Klasse zur Verwaltung von Arrays.
#include <algorithm> //für swap
using namespace std;
class Array
{
private:
unsigned length; //keine negative Länge
int* value;
void copy(int* value, unsigned length)
{
for(unsigned i=0; i<length; ++i)
{
this->value[i]=value[i];
}
}
public:
Array(int* value, unsigned length)
: length(length), value(new int[length])
{
copy(value, length);
}
Array(Array const& other)
: length(other.length), value(new int[other.length])
{
copy(other.value, other.length);
}
Array const& operator=(Array const& other)
{
Array temp(other);
swap(temp);
return *this;
}
~Array()
{
delete [] value;
}
void swap(Array& other)
{
swap(value, other.value);
swap(length, other.length);
}
int& operator[](unsigned index) //für arr[3]=7;
{
return value[index];
}
int const& operator[](unsigned index) const //für const Objekte -> nur lesen
{
return value[index];
}
unsigned size() const
{
return length;
}
Array& operator+=(Array const& other)
{
int* temp=new int[length+other.length];
unsigned i=0;
for(; i<length; ++i)
{
temp[i]=value[i];
}
for(; i<length+other.length; ++i)
{
temp[i]=other.value[i-length];
}
delete [] value;
value=temp;
length+=other.length;
}
};
Array operator+(Array const& a, Array const& b)
{
Array temp(a);
temp+=b;
return temp;
}
bool operator==(Array const& a, Array const& b)
{
if(a.size()!=b.size()) return false;
for(unsigned i=0; i<a.size(); ++i)
{
if(a[i]!=b[i]) return false;
}
return true;
}
bool operator<(Array const& a, Array const& b)
{
if(a.size()<b.size()) return true;
if(a.size()>b.size()) return false;
for(unsigned i=0; i<a.size(); ++i)
{
if(a[i]<b[i]) return false;
}
return true;
}
bool operator!=(Array const& a, Array const& b)
{
return !(a==b);
}
bool operator>(Array const& a, Array const& b)
{
return b<a;
}
bool operator<=(Array const& a, Array const& b)
{
return !(a>b);
}
bool operator>=(Array const& a, Array const& b)
{
return !(a<b);
}