//string类
#include<iostream>
using namespace std;
class String
{
public:
char* GetStr()
{
return _ptr;
}
String(char* str=NULL)
{
if(str==NULL)
{
_ptr=new char[1];
_ptr[0]='\0';
return;
}
_ptr=new char[strlen(str)+1];
strcpy(_ptr,str);
}
void Swap(String& s)
{
char* tmp=s._ptr;
s._ptr=_ptr;
_ptr=tmp;
}
String (const String& s)
:_ptr(NULL)
{
String tmp(s._ptr);
Swap(tmp);
}
String& operator=(String& s)
{
if(this!=&s)
{
String tmp(s._ptr);
Swap(tmp);
}
return *this;
}
~String()
{
delete [] _ptr;
}
private:
char* _ptr;
};
int main()
{
String s1;
cout<<"s1"<<s1.GetStr()<<endl;
String s2("acnkdsn");
cout<<"s2:"<<s2.GetStr()<<endl;
String s3(s2);
cout<<"s3:"<<s3.GetStr()<<endl;
s1 = s3;
cout<<"s1:"<<s1.GetStr()<<endl;
return 0;
}
//顺序表
#include <iostream>
using namespace std;
typedef int DataType;
class SeqList
{
public:
SeqList()
:_array(NULL)
,_size(0)
,_capicity(0)
{}
SeqList(const SeqList& sList)
{
_array = new DataType sizeof[sList._capicity];
memcpy(_array, sList._array,sizeof(DataType)* sList._size);
_size = sList._size;
_capicity = sList._array;
}
SeqList& operator=(const SeqList& sList)
{
if(this != & sList)
{
DataType* tmp = new DataType sizeof[sList._capicity];
memcpy(_array, sList._array,sizeof(DataType)* sList._size);
delete[] _array;
_array = tmp;
_size = tmp._size;
_capicifty = tmp._capicity;
}
}
~SeqList()
{
if(_array)
{
delete[] _array;
}
_size = 0;
_capicity = 0;
}
void PushBack(const DataType& x)
{
_CheckCapicity();
_array[_size++] = x;
}
void PopBack()
{
if(_size)
-- _size;
}
void PushFront(const DataType& x)
{
_CheckCapicity();
for(int i = _size; i > 0; i--)
{
_array[i] = _array[i - 1];
}
_array[0] = x;
_size ++;
}
void PopFront()
{
if(_size)
{
for(int i = 0;i < _size-1; i++)
{
_array[i] = _array[i+1];
}
--_size;
}
}
void Print()
{
for(size_t i = 0;i < _size;++i)
{
cout<<_array[i]<<" "<<endl;
}
}
// 实现上面的函数
void Insert(size_t index, const DataType& x)
{
_CheckCapicity();
for(size_t i = _size;i > index;i--)
{
_array[i] = _array[i - 1];
}
_array[index] = x;
++ size;
}
void Modified (size_t index, const DataType& x)
{
_array[index] = x;
}
void Remove(size_t index)
{
for(size_t i= index;i < _size;i++)
{
_array[i] = _array[i + 1];
}
-- _size;
}
bool Find(const DataType& x, size_t index)
{
for(size_t i = 0;i < size;i++)
{
if(_array[i] == x)
return true;
}
return false;
}
void _CheckCapicity()
{
if(_size == _capicity)
{
_capicity = 2*_capicity + 3;
DataType* tmp = new DataType[_capicity];
memcpy(tmp,_array,sizeof(DataType)*_size);
delete[] _array;
_array = tmp;
}
}
private:
DataType* _array;
size_t _size;
size_t _capicity;
};
void Test1()
{
SeqList s1();
PushBack(s1,2);
PushBack(s1,3);
PushBack(s1,5);
s1.Print();
Find(2,3);
Remove(2);
Remove(0);
Modified(2,5);
}
int main()
{
Test1();
return 0;
}
String类
最新推荐文章于 2022-06-06 08:15:06 发布