String类
#include <iostream>
using namespace std;
class String
{
public:
String(const char *str=nullptr) //处理字符串时,不管传进来的字符串是否为空,都给底层字符串开辟空间,避免之后所有的操作都要对字符串进行判空
{
if (str != nullptr)
{
m_str = new char[strlen(str) + 1];
strcpy(this->m_str, str);
}
else
{
m_str = new char[1];
*m_str = '\0';
}
}
String(const String &src)
{
m_str =new char[strlen( src.m_str)+1];
strcpy(m_str, src.m_str);
}
~String()
{
delete[]m_str;
m_str = nullptr;
}
String & operator=(const String &other) //赋值重载函数
{
if (this == &other)
{
return *this;
}
delete[]m_str;
m_str = new char[strlen(other.m_str) + 1];
strcpy(m_str, other.m_str);
return *this;
}
private:
char *m_str;
};
int main()
{
//调用带参的构造函数
String s1;
String s2("hello");
String s3 = "world";
//调用拷贝构造函数
String s4(s3);
String s5 = s3;
//调用赋值重载阿函数
s1 = s2;
return 0;
}
循环队列
#include <iostream>
using namespace std;
class Queue
{
public:
Queue(int size = 5)
{
_pQue = new int[size];
_front = _rear = 0;
_size = size;
}
~Queue()
{
delete[]_pQue;
_pQue = nullptr;
}
void push(int val)//队尾入队
{
if (full())
resize();
_pQue[_rear] = val;
_rear = (_rear + 1) % _size;
}
void pop()
{
if (empty())
return;
_front = (_front + 1) % _size;
}
int front()
{
return _pQue[_front];
}
bool full()
{
return (_rear + 1) % _size == _front;
}
bool empty()
{
return _front == _rear;
}
private:
int *_pQue; //申请队列的数组空间
int _front; //指示队头
int _rear; //指示队尾
int _size;
void resize()
{
int *ptmp = new int[2 * _size];
int index = 0;
for (int i= _front; i != _rear; i = (i + 1) % _size)
{
ptmp[index++] = _pQue[i];
}
delete[]_pQue;
_pQue = ptmp;
_front = 0;
_rear = index;
_size *= 2;
}
};
int main()
{
Queue queue;
for (int i = 0; i < 20; ++i)
{
queue.push(rand() % 100);
}
while (!queue.empty())
{
cout << queue.front() << " ";
queue.pop();
}
cout << endl;
return 0;
}