Queue in C++ Standard Template Library (STL) - GeeksforGeeks (2024)

Last Updated : 22 Apr, 2023

Improve

Improve

Like Article

Like

Save

Report

Queues are a type of container adaptors that operate in a first in first out (FIFO) type of arrangement. Elements are inserted at the back (end) and are deleted from the front. Queues use an encapsulated object of deque or list (sequential container class) as its underlying container, providing a specific set of member functions to access its elements.

Following is an example to demonstrate the queue and its various methods.

CPP

// CPP code to illustrate Queue in

// Standard Template Library (STL)

#include <iostream>

#include <queue>

using namespace std;

// Print the queue

void showq(queue<int> gq)

{

queue<int> g = gq;

while (!g.empty()) {

cout << '\t' << g.front();

g.pop();

}

cout << '\n';

}

// Driver Code

int main()

{

queue<int> gquiz;

gquiz.push(10);

gquiz.push(20);

gquiz.push(30);

cout << "The queue gquiz is : ";

showq(gquiz);

cout << "\ngquiz.size() : " << gquiz.size();

cout << "\ngquiz.front() : " << gquiz.front();

cout << "\ngquiz.back() : " << gquiz.back();

cout << "\ngquiz.pop() : ";

gquiz.pop();

showq(gquiz);

return 0;

}

Output

The queue gquiz is : 10 20 30gquiz.size() : 3gquiz.front() : 10gquiz.back() : 30gquiz.pop() : 20 30

Methods of Queue are:

The time complexity and definition of the following functions are as follows:

queue::empty()O(1)
queue::size()O(1)
queue::emplace()O(1)
queue::front()O(1)
queue::back()O(1)
queue::push(g)O(1)
queue::pop()O(1)
MethodDefinition
queue::empty()Returns whether the queue is empty. It return true if the queue is empty otherwise returns false.
queue::size()Returns the size of the queue.
queue::swap()Exchange the contents of two queues but the queues must be of the same data type, although sizes may differ.
queue::emplace()Insert a new element into the queue container, the new element is added to the end of the queue.
queue::front()Returns a reference to the first element of the queue.
queue::back()Returns a reference to the last element of the queue.
queue::push(g)Adds the element ‘g’ at the end of the queue.
queue::pop()Deletes the first element of the queue.

C++ program for some more methods

C++

// CPP code to illustrate Queue operations in STL

// Divyansh Mishra --> divyanshmishra101010

#include <iostream>

#include <queue>

using namespace std;

// Print the queue

void print_queue(queue<int> q)

{

queue<int> temp = q;

while (!temp.empty()) {

cout << temp.front()<<" ";

temp.pop();

}

cout << '\n';

}

// Driver Code

int main()

{

queue<int> q1;

q1.push(1);

q1.push(2);

q1.push(3);

cout << "The first queue is : ";

print_queue(q1);

queue<int> q2;

q2.push(4);

q2.push(5);

q2.push(6);

cout << "The second queue is : ";

print_queue(q2);

q1.swap(q2);

cout << "After swapping, the first queue is : ";

print_queue(q1);

cout << "After swapping the second queue is : ";

print_queue(q2);

cout<<q1.empty(); //returns false since q1 is not empty

return 0;

}

Output

The first queue is : 1 2 3 The second queue is : 4 5 6 After swapping, the first queue is : 4 5 6 After swapping the second queue is : 1 2 3 0

The time and space complexities of the operations in this code are as follows:

print_queue function:

Time complexity: O(n), where n is the number of elements in the queue.
Space complexity: O(n), where n is the number of elements in the queue.
q1.push(1), q1.push(2), q1.push(3), q2.push(4), q2.push(5), q2.push(6):

Time complexity: O(1) for each push operation.
Space complexity: O(n), where n is the total number of elements in both queues.
q1.swap(q2):

Time complexity: O(1) for each swap operation.
Space complexity: O(1), as this operation only swaps the internal pointers of the two queues.
q1.empty():

Time complexity: O(1), as this operation simply checks if the queue is empty.
Space complexity: O(1), as no extra space is used for this operation.
Overall, the time and space complexities of this code are reasonable and efficient for typical use cases.

Recent Articles on C++ Queue



`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

Queue in C++ Standard Template Library (STL) - GeeksforGeeks (2024)

FAQs

What C++ library is queue in? ›

Simple Queue in C++

In C++ stl (Standard Template Library) namespace is used to work with Queue, and you need to include a queue library to access all the in-built functions of the Queue by using the syntax: using namespace std, followed by a semi-colon.

What is STL queue in C++? ›

Queues in STL are dynamic storage containers that are implemented as queue data structures in memory. They follow the FIFO (first in first out) arrangement i.e the last element that is inserted will be the last one to be popped out. Elements are stored in a contiguous manner in a queue.

Is C++ Standard Library the same as STL? ›

The STL was created as the first library of generic algorithms and data structures for C++, with four ideas in mind: generic programming, abstractness without loss of efficiency, the Von Neumann computation model, and value semantics. The STL and the C++ Standard Library are two distinct entities.

How to implement a queue in C++? ›

For implementing queue, we need to keep track of two indices, front and rear. We enqueue an item at the rear and dequeue an item from the front. If we simply increment front and rear indices, then there may be problems, the front may reach the end of the array.

Does C++ use deque or queue? ›

Double Ended or Deque Queue is an extended version of the Queue data structure that supports insert and delete operations at both ends. Deque is the short term for "Double-Ended Queue". To use Deque in C++ Standard Template Library, we can use #include<deque> header.

Is queue empty in C++? ›

The queue. empty() function in C++ returns a true (1) value if the queue is empty. Otherwise, it returns false (0) . In short, this function is used to check if the queue is empty or not.

What is STL in C++ with example? ›

The Standard Template Library or STL in C++ is a collection of template classes and template functions that provide a generic way of programming. It is a library of container classes, algorithms, and iterators. It is commonly used for efficiently programming data structures, algorithms, and functions.

Why is STL good for C++? ›

Reusability: One of the key advantages of the STL is that it provides a way to write generic, reusable code that can be applied to different data types. This can lead to more efficient and maintainable code.

How to sort queue in C++ STL? ›

Sorting a Queue without extra space
  1. enqueue() : Adds an item to rear of queue. In C++ STL queue, this function is called push().
  2. dequeue() : Removes an item from front of queue. In C++ STL queue, this function is called pop().
  3. isEmpty() : Checks if a queue is empty. In C++ STL queue, this function is called empty().
Mar 29, 2024

What are the three standard libraries of C++? ›

The Standard C++ Library can be categorized as follows: The Language Support Library. The Diagnostics Library. The General Utilities Library.

Do I need to learn STL in C++? ›

STL proficiency is beneficial for practical coding tasks. DSA skills are often assessed in technical job interviews. Provides tools for quick problem-solving in competitions. Essential for excelling in coding competitions.

What does STL stand for? ›

What is an STL file? STL is a file format commonly used for 3D printing and computer-aided design (CAD). The name STL is an acronym that stands for stereolithography — a popular 3D printing technology.

What are the advantages of queue in C++? ›

Advantages of Queue C++:

It is used in applications in which data is transferred asynchronously between two processes. The queue in C++ can be used for obtaining the synchronization.

How to create a queue in C++ without stl? ›

To implement a double linked list in C++ without using the Standard Template Library (STL), you will need to create a custom class that contains a node object with a pointer to the previous and next node in the list. The node object should contain the data that you wish to store in the list.

How to access queue elements in C++? ›

Front: It is used to access the front elements of the queue in C++. It is an important queue function in C++ as it is responsible for deletion operations. Elements are deleted from the front. Back: It is used to access the rear element of the queue in C++.

What function returns a queue C++? ›

Methods of Queue are:
MethodDefinition
queue::front()Returns a reference to the first element of the queue.
queue::back()Returns a reference to the last element of the queue.
queue::push(g)Adds the element 'g' at the end of the queue.
queue::pop()Deletes the first element of the queue.
4 more rows
Apr 22, 2023

What C++ library is CIN in? ›

The cin object in C++ is an instance of the istream class, which is part of the standard library.

What library is deque in C++? ›

Using a Deque in C++ As we have done in previous sections, we will use the Standard Template Library (STL) of C++ to use a Deque.

References

Top Articles
Latest Posts
Article information

Author: Roderick King

Last Updated:

Views: 5595

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.