STL中的队列是一种容器适配器,以先进先出(FIFO)类型的操作方式运行,其中元素插入到后端(末端),然后从前端删除。在设计复杂的数据结构时,配对队列可能非常有效。第一个元素称为“第一” ,第二个元素称为“第二” ,顺序是固定的(第一,第二)。
句法:
Queue
下面的图像显示了配对队列的工作方式:
以下是显示配对队列的示例:
// C++ program to demonstrate
// the working of STL queue of pairs
#include
using namespace std;
// Print the current pair
void printPair(pair p)
{
// Gives first element from queue pair
int f = p.first;
// Gives second element from queue pair
int s = p.second;
cout << "(" << f << ", " << s << ") ";
}
// Print the Queue of Pairs
void showQueue(queue > gq)
{
// Print element untill the
// queue is not empty
while (!gq.empty()) {
printPair(gq.front());
gq.pop();
}
cout << '\n';
}
// Driver code
int main()
{
queue > gq;
// Pushing elements inside
// the queue container
gq.push({ 10, 20 });
gq.push({ 15, 5 });
gq.push({ 1, 5 });
gq.push({ 5, 10 });
gq.push({ 7, 9 });
cout << "Queue of Pairs: ";
showQueue(gq);
// Prints size of queue
cout
<< "\nSize of Queue of Pairs: "
<< gq.size();
// Prints first element
// of queue container
cout << "\nFront of Queue of Pairs: ";
printPair(gq.front());
// Prints last element
// of queue container
cout << "\nBack of Queue of Pairs: ";
printPair(gq.back());
cout << "\n\nRemoving the Front pair\n";
gq.pop();
cout << "Current Queue of Pairs: ";
showQueue(gq);
return 0;
}
输出:
Queue of Pairs: (10, 20) (15, 5) (1, 5) (5, 10) (7, 9)
Size of Queue of Pairs: 5
Front of Queue of Pairs: (10, 20)
Back of Queue of Pairs: (7, 9)
Removing the Front pair
Current Queue of Pairs: (15, 5) (1, 5) (5, 10) (7, 9)
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。