c++中的双端队列deque

// 第四次练习4.25start.cpp : 定义控制台应用程序的入口点。
#include<iostream>
#include<deque>
#include<algorithm>
using namespace std;
void printDeque(deque<int> &d)
{
	for (deque<int>::iterator it = d.begin(); it != d.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void play03()
{
	deque<int> d1;
	d1.push_back(7);
	d1.push_back(2);
	d1.push_back(8);

	d1.push_front(8);
	d1.push_front(2);
	d1.push_front(3);
	cout << endl;
	cout << "头部元素:" << d1.front() << endl;
	cout << "尾部元素:" << d1.back() << endl;
	printDeque(d1);

	d1.pop_front();
	d1.pop_back();
	printDeque(d1);
	//查找8在数组下标的值
	deque<int>::iterator it = find(d1.begin(), d1.end(), 8);
	if (it != d1.end())
	{
		cout << "8在数组下标的值:" << distance(d1.begin(), it) << endl;
	}
	else
	{
		cout << "没有找到值为8的元素" << endl;
	}
}
int main()
{
	play03();
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是用C++实现双端队列的代码和详细步骤: ```cpp #include <iostream> using namespace std; #define MAXSIZE 100 // 定义双端队列的最大长度 class Deque { private: int data[MAXSIZE]; // 双端队列的数据存储数组 int left; // 左指针 int right; // 右指针 public: Deque() { // 构造函数,初始化左右指针 left = 0; right = 0; } bool isEmpty() { // 判断队列是否为空 return left == right; } bool isFull() { // 判断队列是否已满 return (right + 1) % MAXSIZE == left; } void push_front(int x) { // 在队头插入元素 if (isFull()) { cout << "Deque is full!" << endl; return; } left = (left - 1 + MAXSIZE) % MAXSIZE; data[left] = x; } void push_back(int x) { // 在队尾插入元素 if (isFull()) { cout << "Deque is full!" << endl; return; } data[right] = x; right = (right + 1) % MAXSIZE; } void pop_front() { // 在队头删除元素 if (isEmpty()) { cout << "Deque is empty!" << endl; return; } left = (left + 1) % MAXSIZE; } void pop_back() { // 在队尾删除元素 if (isEmpty()) { cout << "Deque is empty!" << endl; return; } right = (right - 1 + MAXSIZE) % MAXSIZE; } int front() { // 返回队头元素 if (isEmpty()) { cout << "Deque is empty!" << endl; return -1; } return data[left]; } int back() { // 返回队尾元素 if (isEmpty()) { cout << "Deque is empty!" << endl; return -1; } return data[(right - 1 + MAXSIZE) % MAXSIZE]; } }; int main() { Deque dq; dq.push_front(1); dq.push_back(2); dq.push_front(3); dq.push_back(4); cout << dq.front() << endl; // 输出:3 cout << dq.back() << endl; // 输出:4 dq.pop_front(); dq.pop_back(); cout << dq.front() << endl; // 输出:1 cout << dq.back() << endl; // 输出:2 return 0; } ``` 步骤: 1. 定义一个常量MAXSIZE,表示双端队列的最大长度。 2. 定义一个类Deque,包含数据存储数组data和左右指针left、right。 3. 构造函数初始化左右指针。 4. 定义isEmpty()和isFull()函数,分别判断队列是否为空和已满。 5. 定义push_front()和push_back()函数,在队头和队尾插入元素。 6. 定义pop_front()和pop_back()函数,在队头和队尾删除元素。 7. 定义front()和back()函数,分别返回队头和队尾元素。 8. 在main函数创建Deque对象dq,测试双端队列的各种操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值