C++模板实现队列

2023-10-29

我准备练习一下模板的知识,然后自己实现vector类。在这之前,先用模板实现一个队列来热身吧。队列的底层是链表。主要是熟悉一下模板的写法。

另外,就是模板的定义和实现都要写在一个文件中(export关键字可以避免这样。还没用过),所以倒数第二行我加了个# include "queue.hpp",只能是hpp,不能是cpp。不然报错。我用的是4.5.2。

1.queue.h

/*
 * queue.h
 *
 *  Created on: 2011-8-28
 *      Author: gauss
 */

#ifndef QUEUE_H_
#define QUEUE_H_

template<typename T> class queue;

template<typename T>
class queue_item {
	friend class queue<T> ; //注意此处友元类的声明形式
	queue_item(const T& i) :
		item(i), next(0) {
	}
	T item;
	queue_item *next;
};

template<typename T>
class queue {
public:
	queue() :
		head(0), tail(0), n(0) {
	}
	queue(const queue &q);
	queue& operator=(const queue &q);
	~queue();
	void push(const T &i);
	void pop();
	T front();
	T back();
	bool empty() {
		if (n > 0)
			return false;
		else
			return true;
	}
	size_t size() {
		return n;
	}
	void clear();

private:
	queue_item<T> *head;
	queue_item<T> *tail;
	size_t n;
	void copy_item(const queue &q);
};
#include "queue.hpp"               //注意这句话。
#endif /* QUEUE_H_ */

2.queue.hpp

/*
 * queue.hpp
 *
 *  Created on: 2011-8-28
 *      Author: gauss
 */

#ifndef QUEUE_HPP_
#define QUEUE_HPP_

template<typename T>
void queue<T>::push(const T &i) //注意类作用域的形式:queue<T>::
{
	queue_item<T> *item = new queue_item<T> (i);

	if (n == 0) {
		head = tail = item;
	} else {
		tail->next = item;
		tail = item;
	}
	++n;
}

template<typename T>
void queue<T>::pop() {
	if (n > 0) {
		queue_item<T> *temp = head;
		head = head->next;
		delete temp;
		--n;
	}
}

template<typename T>
T queue<T>::front() {                       //这里的返回显然可以是T&
	if (n > 0) {
		return head->item;
	} else {                            //这里处理的不太好,返回了一个默认初始化的T,实现不知道返回什么好
		T t;
		return t;
	}
}

template<typename T>
T queue<T>::back() {                  //这里的返回显然可以是T&
	if (n > 0) {
		return tail->item;
	} else {                      //这里我处理的不太好,反回了一个默认初始化的T,实现不知道返回什么好
		T t;
		return t;
	}
}

template<typename T>
void queue<T>::clear() {
	while (n > 0) {
		pop();
	}
}

template<typename T>
queue<T>::~queue() {
	clear();
}

template<typename T>
queue<T>::queue(const queue &q) :
	head(0), tail(0), n(0) {
	copy_item(q);
}

template<typename T>
queue<T>& queue<T>::operator=(const queue &q)
//注意此处,函数返回类型需此种形式queue<T>&, 不能是queue&
{
	if (this != &q) {
		clear();
		n = 0;
		copy_item(q);
	}
	return *this;
}

template<typename T>
void queue<T>::copy_item(const queue &q) {
	queue_item<T> *temp = q.head;
	while (temp) {
		push(temp->item);
		temp = temp->next;
	}
}
#endif /* QUEUE_HPP_ */

3.main.cpp

#include <cstdlib>
#include <iostream>
#include "queue.h"
#include <string>

using namespace std;

// test the queue class template
int main(int argc, char *argv[]) {
	queue<int> q;
	if (q.empty())
		cout << "empty" << endl;
	else
		cout << "not empty" << endl;
	q.push(1);
	q.push(2);
	queue<int> q2(q);
	q.clear();
	if (q.empty())
		cout << "empty" << endl;
	else
		cout << "not empty" << endl;
	cout << "queue 2: " << q2.front() << endl;
	cout << "queue 2: " << q2.back() << endl;
	cout << "the size of queue 2: " << q2.size() << endl;
	q = q2;
	cout << "queue 1: " << q.front() << endl;
	cout << "queue 1: " << q.back() << endl;

	queue<string> qs;
	qs.push("gauss");
	qs.push("randy");
	qs.push("jiawenjie");
	cout << qs.front() << endl;
	cout << qs.back() << endl;
	return EXIT_SUCCESS;
}


运行结果:

empty
empty
queue 2: 1
queue 2: 2
the size of queue 2: 2
queue 1: 1
queue 1: 2
gauss
jiawenjie


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++模板实现队列 的相关文章

随机推荐

  • 机器学习前沿热点–Deep Learning

    一Deep Learning的前世今生 二Deep Learning的基本思想和方法 三深度学习Deep Learning算法简介 不充分的深度是有害的 大脑有一个深度架构 认知过程看起来是深度的 四拓展学习推荐 五应用实例 六参考链接 深
  • windows server 2012 R2 远程桌面设置中仅允许运行使用网络级别选项灰色

    服务器远程开在外网 装完系统 仅允许使用网络级别身份验证的选项 状态为 灰色未勾选 一段时间之后 很多登录失败 占满内存 只能重启系统 开放外网的远程桌面 未输入凭据 直接到锁屏注销界面登录 致使大量未知用户错误登录 占满系统内存 都属于同
  • 面向前端的webview知识总结

    webview 本篇文主要面向前端同学食用 分别从简介 内核 组件 基本配置 加载 缓存机制 通信等几个方向列举安卓和iOS有关 webview 的知识点 希望前端在和客户端同学对接时不会太懵逼 简介 webview 是一个可以加载网页的可
  • 3.ESP32-S2 USB 挂载SPI-SD,当作U盘使用,无线U盘

    使用的 IDF 4 4 C语言开发 1 ESP32 S2 USB烧录 输出日志 2 ESP32 S2 USB 挂载内部Flash 当作U盘使用 无线U盘 3 ESP32 S2 USB 挂载SPI SD 当作U盘使用 无线U盘 4 ESP32
  • 欧拉函数模板

    欧拉函数 n varphi n n 表示 1 n
  • libvirt 报错

    执行virsh命令出现 下面的错误 error failed to connect to the hypervisor error no valid connection error Failed to connect socket to
  • Nginx 学习笔记01

    Nginx 学习笔记01 概念 Nginx是lgor Sysoev为俄罗斯访问量第二的rambler ru站点设计开发的 从2004年发布至今 凭借开源的力量 已经接近成熟与完善 Nginx功能丰富 可作为HTTP服务器 也可作为反向代理服
  • 打不到VarAsType的解决办法

    在uses单元加入Variants VarType function from Variants unit in Delphi 7 In Delphi 5 VarType function is declared in Systems un
  • 【Verilog基础】7.计数器

    4位计数器 module count4 out reset clk output 3 0 out input reset clk reg 3 0 out always posedge clk begin if reset out lt 0
  • SQL之子查询

    1 案例 案例1 OrderItems表示订单商品表 含有字段订单号 order num 订单价格 item price Orders表代表订单信息表 含有顾客id cust id和订单号 order num OrderItems表 ord
  • matlab 获取向量长度,matlab 获取矩阵和向量长度 length 和 size

    matlab 获取矩阵和向量长度 length 和 size 觉得有用的话 欢迎一起讨论相互学习 概论 size 获取数组的行数和列数 length 数组长度 即行数或列数中的较大值 numel 元素总数 size s size A 当只有
  • 浅谈智能还书车

    智能还书车是一种新型的智能化设备 配备触摸显示屏或简单操作的人机交流界面 图形界面 通过协议或其他网络及专用接口与图书馆自动化系统数据相连接 由读者自行对图书进行快速归还 读者把图书放到书车上 系统自动对图书进行归还操作 无须读者再做其他操
  • postgresql查询锁表pid,SQL、开始时间、执行SQL的ip地址

    SELECT distinct pg stat get backend pid S backendid AS pid pg stat get backend activity start S backendid AS start time
  • Spring Boot 框架介绍和使用

    本文参考自Spring Boot文档 Spring Boot 简介 Spring框架功能很强大 但是就算是一个很简单的项目 我们也要配置很多东西 因此就有了Spring Boot框架 它的作用很简单 就是帮我们自动配置 Spring Boo
  • SpringBoot整合MyBatisPlus显示隐藏打印sql语句日志

    显示 configuration log impl org apache ibatis logging stdout StdOutImpl 不显示 configuration log impl org apache ibatis loggi
  • QueryWrapper多表联查分页、IPage分页(解决IPage+ QueryWrapper 多表联查、条件搜素、模糊匹配的分页问题)

    QueryWrapper多表联查分页 IPage分页 解决IPage QueryWrapper 多表联查 条件搜素 模糊匹配的分页问题 实体类 controller service Impl 重写的mapper xml 最终sql Quer
  • 在shopify中如何使用JavaScript结合开发文档实现不加入购物车直接进入订单支付环节呢?

    今天有一个shopify修改的需求 在shopify中如何使用JavaScript结合开发文档实现不加入购物车直接进入订单支付环节 通过查看开发文档和尝试 发现可以实现 获取到商品信息 然后通过 cart create js接口提交订单 然
  • Matlab学习笔记 奇异值、奇异矩阵、svd函数

    奇异值 奇异值分解法是线性代数中一种重要的矩阵分解法 在信号处理 统计学等领域有重要应用 定义 设A为m n阶矩阵 A 表示A的转置矩阵 A A的n个特征值的非负平方根叫作A的奇异值 记为 i A 如果把A A的特征值记为 i A A 则
  • 前端学习资料汇总

    前端工具 can i see http caniuse com 一个查看css及html5在各个浏览器及手机端的支持情况 前端视野 平时可以多看看的网站了解下最新资讯 前端观察站 腾讯的前端技术 挺有含金量 html5 中国 http ww
  • C++模板实现队列

    我准备练习一下模板的知识 然后自己实现vector类 在这之前 先用模板实现一个队列来热身吧 队列的底层是链表 主要是熟悉一下模板的写法 另外 就是模板的定义和实现都要写在一个文件中 export关键字可以避免这样 还没用过 所以倒数第二行