C++标准库---queue

queue

queue的核心接口主要由成员函数push(),front(),back(),pop()构成;

push():会将一个元素置入queue中;

front():会返回queue内的第一个元素(也就是第一个被置入的元素)

back():会返回queue中的最后一个元素(也就是最后被插入的元素)

pop():会移除queue内的第一个元素(也就是第一个被置入的元素)

注意:
(1)front()和back()仅仅只是返回元素,并不对queue中的元素移除,所以多次执行这两个成员函数,而不执行pop(),返回的结果一样;

(2)pop()虽然执行移除操作,但是并不返回被移除对象的值;

(3)如果想返回queue的元素,并移除返回的元素,就要同时执行fornt()和pop();

(4)如果queue内没有元素,那么front(),back(),pop()的执行都会导致未定义的行为,所以在执行这三个操作是,可以通过size()和empty()判断容器是否为空;


代码示例:

#include<iostream>
#include<queue>
#include<string>

using namespace std;

int main()
{
	queue<string> q;

	q.push("These ");
	q.push("are ");
	q.push("more than ");

	cout<<"back: "<<q.back()<<endl;//返回queue中最后一个元素(也就是最后被插入到队列内的元素)
	cout<<"back: "<<q.back()<<endl;

	cout<<q.front();//返回queue内的第一个元素(也就是最先被插入到队列内的元素)
	q.pop();//移除queue中的第一个元素

	cout<<q.front();
	q.pop();

	q.push("four ");
	q.push("words!");
	q.pop();

	cout<<q.front();
	q.pop();

	cout<<q.front();
	q.pop();

	cout<<endl;

	cout<<"number of elements in the queue: "<<q.size()<<endl;

	system("pause");
	return 0;
}

运行结果:



自己重写queue类,pop()会返回下一个元素,如果queue为空,pop(),front(),back()会抛出异常。

queue.h

#ifndef QUEUE_H
#define QUEUE_H

#include<deque>
#include<exception>

template<class T>
class Queue
{
protected:
	std::deque<T> c;
public:
	class ReadEmptyQueue:public std::exception
	{
	public:
		virtual const char* what() const throw()
		{
			return "read empty queue";
		}
	};
	typename std::deque<T>::size_type size() const 
	{
		return c.size();
	}
	bool empty() const
	{
		return c.empty();
	}
	void push(const T& elem)
	{
		c.push_back(elem);
	}
	
	T& back()
	{
		if(c.empty())
		{
			throw ReadEmptyQueue();
		}
		return c.back();
	}
	
	T& front()
	{
		if(c.empty())
		{
			throw ReadEmptyQueue();
		}
		return c.front();
	}
	T pop()
	{
		if(c.empty())
		{
			throw ReadEmptyQueue();
		}
		T elem(c.front());
		c.pop_front();
		return elem;
	}
};

#endif

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

using namespace std;

int main()
{
	try
	{
		Queue<string> q;

	    q.push("These ");
	    q.push("are ");
	    q.push("more than ");

	    cout<<"back: "<<q.back()<<endl;//返回queue中最后一个元素(也就是最后被插入到队列内的元素)
	    cout<<"back: "<<q.back()<<endl;//两次返回结果一样

	    cout<<q.pop();
	    cout<<q.pop();

    	q.push("four ");
    	q.push("words!");
    	q.pop();

    	cout<<q.pop();
	    cout<<q.pop();

    	cout<<endl;

    	cout<<"number of elements in the queue: "<<q.size()<<endl;

		cout<<q.pop()<<endl;//测试异常
	}
	catch(const exception& e)
	{
		cerr<<"EXCEPTION: "<<e.what()<<endl;
	}

	system("pause");
	return 0;
}

运行结果:


  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值