C++ mein Queue ko use karne ke liye ham Queue STL ka use karte hai. Isme hame Queue ke kuch predefined functions milte hai jinse ham apni DSA problems ko solve kar sakte hai without understand internal implementation of queue.
Lekin agar aapko queue ki internal implementation ko samjhna hai so you go on this article.
Syntax to Include Stack in C++
#include <queue>
using namespace std;
STL ki queue
class C++ ke <queue>
header me hoti hai.
Basic Stack Operations in STL
- Push:
q.push(x);
Queue ke end me element insert karta hai (enqueue). - Pop:
q.pop();
Front se element remove karta hai (dequeue)Top:s.top();
Queue k top element dekhna. - Front:
q.front();
Front element ko return karta hai without removing. - Back:
q.back();
Last element (rear) ko return karta hai. - Empty:
q.empty();
Agar queue empty hai →true
, otherwisefalse
- Size:
q.size();
Queue me kitne elements hain, ye batata hai.
Queu Operations using C++ STL Code
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
q.push(10); // enqueue
q.push(20);
q.push(30);
cout << "Front: " << q.front() << endl;
cout << "Back: " << q.back() << endl;
q.pop(); // dequeue
cout << "Front after pop: " << q.front() << endl;
cout << "Size: " << q.size() << endl;
return 0;
}
Output:
Front: 10
Back: 30
Front after pop: 20
Size: 2
Dry Run Example
queue<int> q;
q.push(5); // queue: [5]
q.push(10); // queue: [5, 10]
q.push(15); // queue: [5, 10, 15]
q.front(); // returns 5
q.back(); // returns 15
q.pop(); // removes 5 → queue: [10, 15]
Ye sab operations O(1)
time complexity me perform hote hain.
Comments