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) |
Method | Definition |
---|---|
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
${secondsToHms(duration)}
${getTagsString(tags)}
'; } 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(); });*/ });