c ++stl队列使用_在C ++ STL中打印队列的所有元素
c ++stl队列使用
To print all elements of a Queue, we follow the following steps:
要打印Queue的所有元素,请执行以下步骤:
Run a loop till “queue is not empty”.
循环运行直到“队列不为空” 。
Print the first (oldest) element by using queue::front() method
通过使用queue :: front()方法打印第一个(最旧的)元素
Remove the oldest element (perform “pop” operation to remove the element)
删除最旧的元素(执行“ pop”操作以删除该元素)
Note: This process will remove all elements of the queue as well. The efficient way is discussed below.
注意:此过程还将删除队列中的所有元素。 有效方法将在下面讨论。
1)正常方式 (1 ) Normal way)
#include <iostream>
#include <queue>
using namespace std;
//Main fubction
int main()
{
// declaring an empty queue
queue<int> Q;
//inserting elements
Q.push(10);
Q.push(20);
Q.push(30);
cout<<"Queue size before printing the elements: "<<Q.size()<<endl;
cout<<"Queue element are..."<<endl;
while(!Q.empty()){
cout<<" "<<Q.front();
Q.pop();
}
cout<<endl;
cout<<"Queue size after printing the elements: "<<Q.size()<<endl;
return 0;
}
Output
输出量
Queue size before printing the elements: 3
Queue element are...
10 20 30
Queue size after printing the elements: 0
Note: See the output, after printing the all elements the size of the Queue is 0 that means all elements have been popped.
注意:查看输出,在打印所有元素后,队列的大小为0,这意味着所有元素都已弹出。
2)高效方式 (2 ) Efficient way)
Here, we can create a copy of the Queue and use that copied queue to print the elements and the another best way is to create a function (using call by value) to print the queue, since we know that function takes the copy of the variable and whatever changes happened with the function variable do not affect to the actual variables.
在这里,我们可以创建Queue的副本,并使用该复制的队列来打印元素,而另一种最佳方法是创建一个函数(使用按值调用)来打印队列,因为我们知道该函数会采用Queue的副本。变量以及函数变量发生的任何变化都不会影响实际变量。
#include <iostream>
#include <queue>
using namespace std;
//function to print the queue
void printQueue(queue<int> q)
{
//printing content of queue
while (!q.empty()){
cout<<" "<<q.front();
q.pop();
}
cout<<endl;
}
//Main fubction
int main()
{
// declaring an empty queue
queue<int> Q;
//inserting elements
Q.push(10);
Q.push(20);
Q.push(30);
cout<<"Queue size before printing the elements: "<<Q.size()<<endl;
cout<<"Queue element are... "<<endl;
printQueue(Q);
cout<<"Queue size after printing the elements: "<<Q.size()<<endl;
return 0;
}
Output
输出量
Queue size before printing the elements: 3
Queue element are...
10 20 30
Queue size after printing the elements: 3
翻译自: https://www.includehelp.com/stl/print-all-elements-of-a-queue.aspx
c ++stl队列使用
还没有评论,来说两句吧...