📜  C++ STL 中的配对队列示例

📅  最后修改于: 2021-09-03 03:09:36             🧑  作者: Mango

STL中的队列是一种容器适配器,它以先进先出 (FIFO)类型的排列方式运行,其中元素在后端(末端)插入并从前端删除。成对队列在设计复杂的数据结构时非常有效。第一个元素被称为“第一” ,第二个元素被称为“第二” ,并且顺序是固定的(第一,第二)。

句法:

下面是显示对队列工作的图像:

以下是显示对队列的示例:

// 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 Classes Live