帮我写一个循环存储的代码
时间: 2023-08-28 16:33:01 浏览: 39
好的,以下是一个简单的循环存储的代码,可以存储整型数据:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 10; // 定义循环数组的最大长度
class CircularArray {
private:
int arr[MAX_SIZE];
int front; // 队首指针
int rear; // 队尾指针
public:
CircularArray() {
front = rear = 0; // 初始化队首队尾指针
}
bool isEmpty() {
return front == rear;
}
bool isFull() {
return (rear + 1) % MAX_SIZE == front;
}
void push(int val) {
if (isFull()) {
cout << "Circular array is full!" << endl;
return;
}
arr[rear] = val;
rear = (rear + 1) % MAX_SIZE;
}
int pop() {
if (isEmpty()) {
cout << "Circular array is empty!" << endl;
return -1;
}
int val = arr[front];
front = (front + 1) % MAX_SIZE;
return val;
}
};
int main() {
CircularArray ca;
// 向循环数组中添加元素
ca.push(1);
ca.push(2);
ca.push(3);
ca.push(4);
ca.push(5);
ca.push(6);
// 从循环数组中取出元素
cout << ca.pop() << endl; // 1
cout << ca.pop() << endl; // 2
cout << ca.pop() << endl; // 3
cout << ca.pop() << endl; // 4
cout << ca.pop() << endl; // 5
cout << ca.pop() << endl; // 6
cout << ca.pop() << endl; // Circular array is empty!
return 0;
}
```
在上述代码中,我们定义了一个长度为10的循环数组,通过 `push()` 方法向数组中添加元素,通过 `pop()` 方法从数组中取出元素。同时,我们通过 `isEmpty()` 和 `isFull()` 方法判断循环数组是否为空或已满。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)