緒:
看法式碰到queue隊列的利用方式;
下面經由過程一個例程來簡要概述一下queue隊列的常識點:
什么是隊列;挨次隊列;
C++:queue隊列的用法;
模板類;
queue應用例程:
#include <queue>
#include <iostream>
using namespace std;
int main()
{
queue<int> myQ;
for(int i=0; i<10; i++)
myQ.push(i);
cout<<"myQ size is: "<<myQ.size()<<endl;
for(int i=0; i<myQ.size(); i++)
{
cout << myQ.front()<<endl;
myQ.pop();
}
cout<<"myQ size is: "<<myQ.size()<<endl;
return 0;
}
什么是隊列?
隊列是一種特別的線性表,
特別之處在于:它只許可在表的前端進行刪除操作,只許可在表的后端進行插入操作;
隊列是一種操作受限制的線性表;
進行插入操作的端稱為隊從頭至尾,進行刪除操作的端稱為隊頭。隊列中沒有元素時,稱為空隊列。
隊列的數據元素又稱為隊列元素。
在隊列中插入一個隊列元素稱為入隊,
從隊列中刪除一個隊列元素稱為出隊。
因為隊列只許可在一端插入,在另一端刪除,所以只有最早進入隊列的元素才能最先從隊列中刪除,故隊列又稱為進步前輩先出(FIFO—first in first out)線性表。
挨次隊列:
成立挨次隊列布局必需為其靜態分派或動態申請一片持續的存儲空間,并設置兩個指針進行辦理。
一個是隊頭指針front,它指標的目的隊頭元素;
另一個是隊從頭至尾指針rear,它指標的目的下一個入隊元素的存儲位置,
如圖所示:
C++中的queue:
queue是STL的隊列,有FIFO的特征。
①隊列頭文件:#include <queue>
②queue模板類:需要兩個模板參數,
一個是元素類型,一個容器類型,
元素類型是需要的,容器類型是可選的,默認為deque類型。
界說queue對象的示例代碼如下:
queue<int> q1;
queue<double> q2;
queue<Point> q3;
queue的根基操作有:
入隊,如例:q.push(x); 將x接到隊列的結尾。
出隊,如例:q.pop(); 彈出隊列的第一個元素,注重,并不會返回被彈出元素的值。
拜候隊首元素,如例:q.front(),即最早被壓入隊列的元素。
拜候隊從頭至尾元素,如例:q.back(),即最后被壓入隊列的元素。
判定隊列空,如例:q.empty(),當隊列空時,返回true。
拜候隊列中的元素個數,如例:q.size()
queue的應用:
#include "stdafx.h"
#include <queue>
#include <iostream>
#include <string>
using namespace std;
void test_empty()
{
queue<int> myqueue;
int sum (0);
for (int i=1;i<=10;i++)
myqueue.push(i);
while (!myqueue.empty())
{
sum += myqueue.front();
myqueue.pop();
}
cout << "total: " << sum << endl;
}
void test_pop()
{
queue<int> myqueue;
int myint;
cout << "\nPlease enter some integers (enter 0 to end):\n";
do
{
cin >> myint;
myqueue.push (myint);
} while (myint);
cout << "myqueue contains: ";
while (!myqueue.empty())
{
cout << " " << myqueue.front();
myqueue.pop();
}
}
void test_size()
{
queue<int> myints;
cout << "0. size: " << (int) myints.size() << endl;
for (int i=0; i<5; i++) myints.push(i);
cout << "1. size: " << (int) myints.size() << endl;
myints.pop();
cout << "2. size: " << (int) myints.size() << endl;
}
int main()
{
test_empty();
cout<<"\n***********************************************\n";
test_size();
cout<<"\n***********************************************\n";
test_pop();
cout<<"\n***********************************************\n";
queue<string> q;
// insert three elements into the queue
q.push("These ");
q.push("are ");
q.push("more than ");
//cout << "number of elements in the queue: " << q.size()<< endl;
// read and print two elements from the queue
cout << q.front();
q.pop();
cout << q.front();
q.pop();
//cout << "number of elements in the queue: " << q.size()<< endl;
// insert two new elements
q.push("four ");
q.push("words!");
// skip one element
q.pop();
// read and print two elements
cout << q.front();
q.pop();
cout << q.front() << endl;
q.pop();
cout << "number of elements in the queue: " << q.size()<< endl;
return 0;
}
0 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!