queue
queue的核心接口主要由成员函数push(),front(),back(),pop()构成;
注意:
(1)front()和back()仅仅只是返回元素,并不对queue中的元素移除,所以多次执行这两个成员函数,而不执行pop(),返回的结果一样;
运行结果:
运行结果:
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;
}
运行结果: