型,元素類型是必要的,容器類型是可選的,默認為deque 類型??蛇x的容器類型有queue,list,但是不能用vector;
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()判斷容器是否為空;
代碼示例:
[cpp] view plain copy#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
[cpp] view plain copy#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 [cpp] view plain copy#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; } 運行結果:新聞熱點
疑難解答
圖片精選